我有一个 main.cpp 文件和两个类,每个类都有一个 .h 文件和一个 .cpp 文件。Main.cpp 包含每个类的 .h 文件并毫无问题地使用这些类。我可以让一个班级使用另一个班级。
我尝试将一个类的 .h 文件包含在另一个类中,但已经声明错误。
我尝试在另一个类中声明该类,但得到不完整的声明错误。
我花了一个多小时阅读其他堆栈溢出答案和其他网站,但我发现没有什么是相同的(其中大多数是主类和一个类的问题)。
main.cpp 有:
//other includes
#include "class1.h"
#include "class2.h"
int main( int argc, char* args[] )
{
Class1 classOne;
//code that use classOne and works
Class2 classTwo;
//code that tries to use classTwo
}
类1.h
class Class1
{
//some things
}
class1.cpp 无关紧要,因为从 main.cpp 使用时,其中的所有内容都有效
类2.h
class Class2
{
Class1 classInside; //"does not name a type" error
public:
void DoSomething(Class1* getClass); //"has not been declared" error
void DoSomethingElse();
}
类2.cpp
#include "class2.h"
Class2::DoSomethingElse()
{
Class1 classOneInsideWorkAlready; //"has not been declared" error
}
尝试了许多在 class2 中使用 class1 的方法,但都没有奏效。
在我的项目中,我尝试创建一个class1的实例,在main中使用它,然后创建一个class2的实例(直到这里一切正常)并调用class2实例内部的方法来修改class1的实例(通过使用定义的公共方法在类 1) 内。
Class2 是程序的一部分,一旦用户想要使用另一部分(Class3)就会被丢弃,因此无需将其保存在内存中。Class1 关心用户看到的内容,所以当用户从 Class2 更改为 Class3 时,我不希望它消失。
希望这有点道理,感谢您的阅读。