c++ - 声明类解决无效使用不完整类型错误
问题描述
我是 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;
};
解决方案
澄清一下,cpVector 依赖于 cpScalar,反之亦然 - 需要循环依赖
我认为没有理由相信这一点。您可能认为需要循环依赖,但事实并非如此。想想你是如何了解这些概念的。您可能早在上学之前就已经了解了标量(以计数的形式)。另一方面,向量往往是一门更高级的学科,它建立在你对标量的了解(在高中或几年前?)的基础上。
程序中的结构可能是相似的:标量应该可以自己定义,而向量则建立在标量之上。当向量和标量交互时(例如将向量乘以标量),定义应该属于更“高级”的类,即cpVector
. 不需要循环依赖。
推荐阅读
- python - 与另一个程序调用的 Python 脚本交互的最简单方法是什么?
- powershell - Powershell - 找不到模块
- python - 如何在 QSortFilterProxyModel 中检索当前过滤的元素内部 filterAcceptsRow 方法
- java - (已回答)在普通 Java 中是否有与 OpenGL 中的 GL_SCISSOR 方法等效的方法?
- excel - 无法使用 VBA 中的“wininet.dll”连接到 FTP 服务器,但可以使用 WinSCP 连接
- angular - Angular 9 i18n 迁移 - 测试失败
- angular - 如何将相关数据的发布请求从 Angular 发送到 .NET 核心 api
- c++ - 如何将数组直接传递给 C++ 构造函数
- c - 在C中的二维数组中搜索子字符串
- office-js - 多个 Word/Office 加载项交互