提问人:Theodore 提问时间:6/26/2020 最后编辑:EdricTheodore 更新时间:6/26/2020 访问量:259
如何在类定义(头文件)、类声明(源文件)和主功能(源文件)中拆分代码?
How do I split the code in class definition (header file), class declaration (source file) and the main funtion (source file)?
问:
我在定义文件中都包含头文件,并在主文件中包含了头文件。 但我不明白为什么会出现这些错误:
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;
}
答: 暂无答案
评论
test.cpp