I included the header file in both the definitions file and int the main file. But I don't understand why I get these errors:
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&)'
I split the code like below. What am I missing? Thanks for your answers!
test.h file, with declarations:
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 file, with definitions:
#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";
}
and main.cpp file, with the actual program:
#include "test.h"
int main()
{
Test test1;
Test test2(2, "test2", 't');
cout << "test1: " << test1;
cout << "test2: " << test2;
}