48 c++ compiler-construction class
我正在尝试使用以下命令在C++中编译2个类:
g++ Cat.cpp Cat_main.cpp -o Cat
但是我收到以下错误:
Cat_main.cpp:10:10: error: variable ‘Cat Joey’ has initializer but incomplete type
有人可以向我解释这意味着什么吗?我的文件基本上是创建一个class(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;
}
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
Luc*_*ore 45
当您需要完整类型时,可以使用前向声明.
您必须具有该类的完整定义才能使用它.
通常的方法是:
1)创建一个文件 Cat_main.h
2)搬家
#include <string>
class Cat
{
public:
Cat(std::string str);
// Variables
std::string name;
// Functions
void Meow();
};
Run Code Online (Sandbox Code Playgroud)
到Cat_main.h
.请注意,我删除了标题内部using namespace std;
并使用了限定字符串std::string
.
3)包括在这两个文件Cat_main.cpp
和Cat.cpp
:
#include "Cat_main.h"
Run Code Online (Sandbox Code Playgroud)
您不能定义不完整类型的变量。您需要将 的整个定义纳入Cat
范围,然后才能在 中创建局部变量main
。我建议您将类型的定义移至Cat
标头,并将其包含在具有main
.