C++ 变量有初始值设定项但类型不完整?

问题描述 投票:0回答:5

我正在尝试使用以下命令编译 C++ 中的 2 个类:

g++ Cat.cpp Cat_main.cpp -o Cat

但是我收到以下错误:

Cat_main.cpp:10:10: error: variable ‘Cat Joey’ has initializer but incomplete type

有人能给我解释一下这是什么意思吗?我的文件基本上做的是创建一个类(

Cat.cpp
)并创建一个实例(
Cat_main.cpp
)。这是我的源代码:

Cat_main.cpp:

#include <iostream>
#include <string>

class Cat;

using namespace std;

int main()
{
    Cat Joey("Joey");
    Joey.Meow();

    return 0;
}

Cat.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;
}
c++ class compiler-construction
5个回答
57
投票

当您需要完整类型时,可以使用前向声明。

您必须拥有该类的完整定义才能使用它。

通常的方法是:

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"

18
投票

有时,当您

forget to include the corresponding header
时,也会发生同样的错误。


16
投票

这与 Ken 的情况没有直接关系,但如果您复制 .h 文件并忘记更改

#ifndef
指令,也可能会发生此类错误。在这种情况下,编译器将跳过类的定义,认为它是重复的。


5
投票

不能定义不完整类型的变量。您需要将

Cat
的整个定义带入范围 ,然后才能在 main
 中创建局部变量。我建议您将类型 
Cat
 的定义移至标题,并将其包含在具有 
main
 的翻译单元中。


1
投票
我遇到了类似的错误,并在搜索解决方案时点击了此页面。

对于 Qt,如果您忘记在构建中添加

QT_WRAP_CPP( ... )

 步骤来运行元对象编译器 (moc),则可能会发生此错误。包含 Qt 标头是不够的。

© www.soinside.com 2019 - 2024. All rights reserved.