【发布时间】:2023-03-27 03:05:02
【问题描述】:
我正在编写一个简单的类并得到一些错误。头文件如下图:
//
// temp.h
//
#ifndef _TEMP_h
#define _TEMP_h
#include <string>
using namespace std;
class GameEntry {
public:
GameEntry(const string &n="", int s=0);
string getName();
int getScore();
private:
string name;
int score;
};
#endif
方法文件如下图:
// temp.cpp
#include "temp.h"
#include <string>
using namespace std;
GameEntry::GameEntry(const string &n, int s):name(n),score(s) {}
string GameEntry::getName() { return name; }
int GameEntry::getScore() { return score; }
主文件如下图:
#include <iostream>
#include <string>
#include "temp.h"
using namespace std;
int main() {
string str1 = "Kenny";
int k = 10;
GameEntry G1(str1,k);
return 0;
}
我收到这样的错误:
Undefined symbols for architecture x86_64:
"GameEntry::GameEntry(std::__1::basic_string<char, std::__1::char_traits<char>,
std::__1::allocator<char> > const&, int)", referenced from:
_main in main1-272965.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
谁能告诉我怎么了?非常感谢。
【问题讨论】:
-
您是如何调用编译器和链接器的?好像你忘了链接
temp.o。 -
你是怎么编译的?什么是命令行?
-
我只是简单地尝试“c++ main.cpp”,它通常对我有用。
-
您需要将
temp.cpp编译成一个目标文件(temp.o) 并将其与main.cpp 链接。试试g++ -c temp.cpp和g++ main.cpp temp.o。这是对以下答案中的更正的补充。 -
是的,这解决了问题。不过,我不太明白。我认为对于类似的实现,甚至更大的类,我通常只在 main 中包含头文件,并且只使用“c++ main.cpp”。你能提供更多这样做的理由吗?
标签: c++ string class reference