运算符重载c ++ /在哪里放我的代码?

fti*_*sem 5 c++ operator-overloading

今天我在我的一个课程中重载了<<运算符:

#ifndef TERMINALLOG_HH
#define TERMINALLOG_HH

using namespace std;

class Terminallog {
public:

    Terminallog();
    Terminallog(int);
    virtual ~Terminallog();

    template <class T>
    Terminallog &operator<<(const T &v);

private:

};

#endif
Run Code Online (Sandbox Code Playgroud)

如您所见,我在头文件中定义了重载运算符,然后我继续在我的.cc文件中实现它:

//stripped code

template <class T>
Terminallog &Terminallog::operator<<(const T &v) {
    cout << endl;
    this->indent();
    cout << v;
    return *this;
}

//stripped code
Run Code Online (Sandbox Code Playgroud)

然后我使用我的新类创建了一个main.cpp文件:

#include "inc/terminallog.hh"

int main() {
    Terminallog clog(3);
    clog << "bla";
    clog << "bla";
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我继续前进:

g++ src/terminallog.cc inc/terminallog.hh testmain.cpp -o test -Wall -Werror 
/tmp/cckCmxai.o: In function `main':
testmain.cpp:(.text+0x1ca): undefined reference to `Terminallog& Terminallog::operator<< <char [4]>(char const (&) [4])'
testmain.cpp:(.text+0x1de): undefined reference to `Terminallog& Terminallog::operator<< <char [4]>(char const (&) [4])'
collect2: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)

BAM!一个愚蠢的链接器错误,我仍然不知道它来自哪里.我玩了一下,注意到我的重载操作符的实现在我的头文件中解决了所有问题.现在我比以前更加困惑了.

为什么我不能将重载运算符的实现放在我的.cc文件中?当我把它放在我的头文件中时,它为什么运行顺畅?

事先感到困惑

ftiaronsem

paj*_*ton 1

可以在 cpp 文件中保留实现,但您需要为您使用的每种类型声明模板的用法。请参阅Parashift C++ 常见问题解答以获取更详细的说明。

对于您的情况,您必须在 cpp 文件中的某个位置写入该行:

template Terminallog &Terminallog::operator<<(const char* &v);
Run Code Online (Sandbox Code Playgroud)