假设有一个源文件un2.cpp
----un2.cpp----
class employee;
void employee::setname(string s)
{
.....(some code)
}
employee 类在 un2.h 中定义,其中声明了 setname()。 现在,当我尝试通过“cc -c un2.cpp -o un2.o”编译 un2.cpp 时,我收到一条错误消息
un2.cpp:3:16: error: invalid use of incomplete type ‘struct employee’
un2.cpp:1:7: error: forward declaration of ‘struct employee’
为什么编译器不直接将 employee 作为外部符号(就像它会采用先前声明但 undefined symbol 一样)并编译 un2.cpp 文件。
编译一个普通的undefined symbol和一个undefined class有什么区别吗? 还有谁能告诉我(如果可能的话)如何转发声明一个类并在其中定义符号吗?
最佳答案
external 用于链接器,在您编译代码时不会帮助您,因为编译器仅通过编写前向声明不知道您的类声明。
相反,您需要在 un2.cpp 文件中包含带有声明的 header 才能编译。
关于c++ - 编译包含在 header 中声明的函数的源文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11969778/