我正在尝试使用以下命令在 C++ 中编译 2 个类:
g++ Cat.cpp Cat_main.cpp -o Cat
但我收到以下错误:
Cat.cpp:10:10: 错误:变量“Cat Joey”具有初始化程序但类型不完整
谁能给我解释一下这是什么意思?我的文件基本上做的是创建一个类 (Cat.cpp
) 并创建一个实例 (Cat_main.cpp
)。这是我的源代码:
Cat.cpp:
#include <iostream>
#include <string>
class Cat;
using namespace std;
int main()
{
Cat Joey("Joey");
Joey.Meow();
return 0;
}
Cat_main.cpp:
#include <iostream>
#include <string>
using namespace std;
class Cat
{
public:
Cat(string str);
// Variables
string name;
// Functions
void Meow();
};
Cat::Cat(string str)
{
this->name = str;
}
void Cat::Meow()
{
cout << "Meow!" << endl;
return;
}
最佳答案
当你需要一个完整的类型时,你使用前向声明。
您必须拥有该类的完整定义才能使用它。
通常的做法是:
1) 创建文件Cat_main.h
2) 移动
#include <string>
class Cat
{
public:
Cat(std::string str);
// Variables
std::string name;
// Functions
void Meow();
};
到 Cat_main.h
。请注意,在标题中,我删除了 using namespace std;
和带有 std::string
的限定字符串。
3) 将此文件包含在 Cat_main.cpp
和 Cat.cpp
中:
#include "Cat_main.h"
关于C++变量具有初始化程序但类型不完整?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9770980/