C++变量具有初始化程序但类型不完整?

标签 c++ class compiler-construction

我正在尝试使用以下命令在 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.cppCat.cpp 中:

#include "Cat_main.h"

关于C++变量具有初始化程序但类型不完整?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9770980/

相关文章:

class - 是否可以找到已编译的 java 文件的 jdk 供应商

compiler-construction - 反斜杠 "\"到底是什么意思?

c++ - 为什么我不能定义没有常量的比较

c++ - 经过一段时间后,是否有办法从流程中分离流程?

C++ ifstream 声明为公共(public)的,但编译器说它是一个无法访问的私有(private)成员

c++ - (cin >> buf && !buf.empty()) 中的第二个条件是否多余?

algorithm - 不可变语言如何高效地实现 set、concat、equals 等?

c++ - 如何在 operator += 中调用 operator +

c# - 试图创建一个包含结构的数组?

python - 我对 OOP 中对象的行为有点困惑