首页 > 解决方案 > 声明类解决无效使用不完整类型错误

问题描述

我是 C++ 新手,正在尝试使用两个 .hpp 文件 cpScalar.hpp 和 cpVector.hpp 作为分配进行计算。我在阅读前向声明解释时遇到了困难 - 我发现的所有解决方案都说我不能在完全“声明类”之前使用另一个标题中另一个类的方法,而且我不知道我必须做什么才能“完全声明/定义”类。

澄清一下,cpVector 依赖于 cpScalar,反之亦然 - 需要循环依赖

我打算使用 cpScalar 来获取 cpVector 中的 cpScalar 数组,但是我无法访问参数输入 'cpScalar sarr[]',因为我没有声明,并且正在使用不完整类型错误。我想知道我需要为这部分做些什么。

我不打算在构造函数中使用指针代替向量,因为这会导致灵活的数组问题,这些问题(似乎)可以使用我在课堂上没有学习的“struct”和“malloc”来解决。

下面是我的代码:

// cpVector
#ifndef CPVECTOR_HPP
#define CPVECTOR_HPP
#include <iostream>
#include <vector>
#include "cpScalar.hpp"

using namespace std;

class cpScalar;

class cpVector{
private:
    vector<cpScalar> arr; // cpScalar* arr; seems to be more complicated...
    unsigned int size;

public:
    cpVector(cpScalar sarr[], unsigned int size2){ // this constructor is given
        this->size = size2;
        arr.resize(size);
        for (int i =0; i<size; i++){
            arr[i] = sarr[i]; // this gives incomplete type error
        }
        };
... more public functions...

#endif



#ifndef CPSCALAR_HPP
    #define CPSCALAR_HPP
    #include <iostream>
    #include <string>
    #include "cpVector.hpp"

using namespace std;

class cpVector;

class cpScalar{
private:
    int intScalar;
    double doubScalar;


public:
    cpScalar(int num){
        intScalar = num;
    };

    cpScalar(double num){
        doubScalar = num;
    };

标签: c++

解决方案


澄清一下,cpVector 依赖于 cpScalar,反之亦然 - 需要循环依赖

我认为没有理由相信这一点。您可能认为需要循环依赖,但事实并非如此。想想你是如何了解这些概念的。您可能早在上学之前就已经了解了标量(以计数的形式)。另一方面,向量往往是一门更高级的学科,它建立在你对标量的了解(在高中或几年前?)的基础上。

程序中的结构可能是相似的:标量应该可以自己定义,而向量则建立在标量之上。当向量和标量交互时(例如将向量乘以标量),定义应该属于更“高级”的类,即cpVector. 不需要循环依赖。


推荐阅读