gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:26:48 25 4
gpt4 key购买 nike

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

#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

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

//stripped code

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

//stripped code

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

#include "inc/terminallog.hh"

int main() {
Terminallog clog(3);
clog << "bla";
clog << "bla";
return 0;
}

然后我继续编译:

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

砰!一个愚蠢的链接器错误,我仍然不知道它来自哪里。我试了一下,发现将重载运算符的实现放在头文件中可以解决所有问题。现在我比以前更糊涂了。

为什么我不能将重载运算符的实现放在我的 .cc 文件中?为什么我把它放到我的头文件里就可以顺利运行了?

提前致谢

亚伦森

最佳答案

编译器必须看到实现才能使用模板。通常这意味着您将它放在页眉中。

关于c++ - 运算符重载 C++/我的代码放在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5449986/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com