c++ - C++中的前向声明错误

标签 c++ compiler-errors forward-declaration

<分区>

我在 hpp 文件中定义了一个类,我正试图在另一个 header 中使用它,因此我对它做了一个前向声明(我只想通过引用将其用作函数参数)。出于某种原因,我不断收到编译错误。我不知道为什么它不起作用。这是我的代码:

//something.hpp:
class MyClass;
void someFunction (MyClass& mc);
...

//something.cpp:
#include "MyClass.hpp"
void someFunction (MyClass& mc) {...}
...

//MyClass.hpp:
class MyClass {
    const char* myText;
public:
    MyClass (const char* text) : myText(text) {}
};

//main.cpp:
int main () {
    ...
    someFunction (MyClass ("some text here"));
    ...
}

我从 main() 得到一个错误,它说:

'<function-style-cast>' : cannot convert from 'const char [15]' to 'MyClass'
Source or target has incomplete type

如果我理解正确,这意味着编译器没有找到 MyClass 的定义,只有它的预声明(即使我在 something.cpp 中包含了 MyClass.hpp),这就是为什么它说它不完整。我在这里错过了什么?

最佳答案

函数

void someFunction (MyClass& mc);

正在接受对 MyClass 实例的非常量引用。

您不能将临时值传递给此类函数。

代码应该是

 #include "MyClass.hpp"
 ...
 int main() {
     MyClass m("some text here");
     someFunction(m);
 }

或者您需要接受一个常量引用。

void someFunction (const MyClass& mc);

关于c++ - C++中的前向声明错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29428670/

相关文章:

c++ - 在字段声明中使用 "struct Foo"不会转发声明嵌套类

c++ - STL vector reserve() 和 copy()

c++ - 编译器支持即将推出的 C++0x

c# - 没有名为 fcntl 的模块

c++ - 在 C++ 中,是否可以将一个类声明为从另一个类继承?

c++ - 使用默认值转发声明类

c++ - 如何管理标题的#include?

c++ - 如何检查字符串的长度并返回带有前导零的值

java - 为什么此代码有这么多错误?

compiler-errors - Fortran 编译错误 : Unclassifiable statement