首页 > 解决方案 > 如何拆分类定义(头文件)、类声明(源文件)和主函数(源文件)中的代码?

问题描述

我在定义文件和主文件中都包含了头文件。但我不明白为什么会出现这些错误:

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++windowsundefined-reference

解决方案


推荐阅读