C++变量有初始值但不完整的类型?

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.cppCat.cpp:

#include "Cat_main.h"
Run Code Online (Sandbox Code Playgroud)

  • @Ken很简单,但它有很大的不同.您应该阅读C++的入门书籍,其中详细解释了这些概念,除此之外还有更多内容. (3认同)
  • @Ken 不,那不是我说的。再次阅读答案。 (2认同)

Dmi*_*rev 11

它与Ken的案例没有直接关系,但如果您复制.h文件并忘记更改#ifndef指令,也会发生这样的错误.在这种情况下,编译器将跳过认为它是重复的类的定义.


Dav*_*eas 5

您不能定义不完整类型的变量。您需要将 的整个定义纳入Cat范围,然后才能在 中创建局部变量main。我建议您将类型的定义移至Cat标头,并将其包含在具有main.

  • @Ken:不,你必须阅读一本关于 C++ 的介绍书,其中将解释头文件和源文件的概念。 (5认同)

xtl*_*luo 5

有时,当您使用forget to include the corresponding header.