【发布时间】:2019-01-28 09:00:21
【问题描述】:
我在 Cat.h 文件中定义了一个类 Cat,它有一个成员函数 void Cat::miao()。然后,我在 Cat.cpp 中实现了这个函数,代码如下。
但是,在编译和链接时,我得到了一个错误,比如“未定义对`Cat::miao()的引用”。代码有什么问题?
我的编译器是 GNU c11。
-----猫.h
#include<iostream>
#include<string>
using namespace std;
class Cat
{
string name;
public:
Cat(const string&n):name(n){};
void miao();
};
-----Cat.cpp
#include"Cat.h"
void Cat::miao()
{
cout << name << endl;
}
-----main.cpp
#include"Cat.h"
int main()
{
Cat tom("tom");
tom.miao();
return 1;
}
编译:
g++ main.cpp
导致此错误:
C:\Users****:K.o:main.cpp:(.text+0x69): 未定义对 `Cat:: 的引用 喵()' collect2.exe:错误:ld 返回 1 个退出状态
【问题讨论】:
-
这看起来像是一个链接问题 - 你能粘贴用于编译(/链接)你的程序的确切命令吗?
-
Windows 8 中的命令“g++ main.cpp”
-
你没有编译
Cat.cpp。试试g++ main.cpp Cat.cpp -
@W.Cameron 您需要添加
cat.cpp,例如g++ main.cpp cat.cpp。 -
@W.Cameron 检查答案是否可行。