今天我重載< <運營商在我的一類:運算符重載C++ /在哪裏把我的代碼?
#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;
}
和我去上compilying:
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
BAM!一個愚蠢的鏈接器錯誤,我仍然不知道它來自哪裏。我玩了一下,注意到將我的重載操作符的實現放在我的頭文件中解決了所有問題。現在我比以前更困惑了。
爲什麼我不能在我的.cc文件中實現重載操作符?爲什麼當我把它放在我的頭文件中時它運行平穩?
困惑在此先感謝
ftiaronsem
見http://stackoverflow.com/questions/3749099/why-should-the-implementation - 模板類的聲明 – Erik 2011-03-27 14:53:55
鏈接器錯誤絕不是愚蠢的 - 它們只是編譯器錯誤的信息。 – quamrana 2011-03-27 14:55:04
@ftiaronsem:順便說一句 - 不要在頭文件中放置'using namespace std;' - 你可以把它放在'cc'文件中,然後在頭文件中根據需要使用'std ::'限定符。 – quamrana 2011-03-27 15:01:31