今天,我在我的一个类中重载了<<操作符:
#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文件中?为什么当我把它放到头文件中时,它运行得很流畅?
困惑的提前道谢
ftiaronsem
发布于 2011-03-27 23:00:28
可以将实现保存在cpp文件中,但您需要为要使用模板的每种类型声明其用法。更详细的解释请参考Parashift C++ Faq。
在本例中,您必须将该行写入cpp文件中的某个位置:
template Terminallog &Terminallog::operator<<(const char* &v);发布于 2011-03-27 22:53:07
编译器必须看到实现才能使用模板。通常这意味着你把它放在头中。
发布于 2011-03-27 22:57:08
除了@Bo的回答:你应该阅读C++ FAQ Lite:http://www.parashift.com/c++-faq-lite/templates.html#faq-35.12中的文章,以及更多。
https://stackoverflow.com/questions/5449986
复制相似问题