c++ - 如何拆分类定义(头文件)、类声明(源文件)和主函数(源文件)中的代码?
问题描述
我在定义文件和主文件中都包含了头文件。但我不明白为什么会出现这些错误:
undefined reference to `Test::Test()'
undefined reference to `Test::Test(int, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, char)'
undefined reference to `operator<<(std::ostream&, Test const&)'
undefined reference to `operator<<(std::ostream&, Test const&)'
我将代码拆分如下。我错过了什么?感谢您的回答!
test.h 文件,带有声明:
class Test
{
public:
Test(int i1, string s1, char c1);
//const Test &default_test();
Test();
int get_i() const { return i; }
string get_s() const { return s; }
char get_c() const { return c; }
private:
int i;
string s;
char c;
};
ostream &operator<<(ostream &os, const Test &t);
test.cpp 文件,包含定义:
#include "test.h"
Test::Test(int i1, string s1, char c1)
: i{i1}, s{s1}, c{c1}
{
}
const Test &default_test()
{
static Test t{1, "test1", 't'};
return t;
}
Test::Test()
: i{default_test().get_i()},
s{default_test().get_s()},
c{default_test().get_c()}
{
}
ostream &operator<<(ostream &os, const Test &t)
{
return os << t.get_i() << " " << t.get_s() << " " << t.get_c() << "\n";
}
和 main.cpp 文件,带有实际程序:
#include "test.h"
int main()
{
Test test1;
Test test2(2, "test2", 't');
cout << "test1: " << test1;
cout << "test2: " << test2;
}
解决方案
推荐阅读
- c++ - 在 C++ 中输出非常大的数字
- jquery - 如何使用 jQuery 仅检索一个 div 的文本?
- python - 从网站(metacritc)Python中抓取数据时如何匹配数组长度
- adobe-indesign - indesign cs5编号列表未排序
- javascript - 导航栏行为怪异
- javascript - supertest的expect和then的区别?
- python - 将 subprocess.Popen 的返回值保存到全局变量
- python - 如何组合 Scrapy 输出
- python - 根据第二个 csv 过滤一个 csv
- python-2.7 - UnicodeDecodeError:“utf8”编解码器无法解码位置 3 中的字节 0xaf:python 2.7 中的无效起始字节