看板 C_and_CPP 關於我們 聯絡資訊
==== 編譯環境 ==== Using built-in specs. Target: i386-undermydesk-freebsd Configured with: FreeBSD/i386 system compiler Thread model: posix gcc version 4.2.1 20070719 [FreeBSD] ==== 程式碼 ==== #include <iostream> template <typename T> class Test; template <typename T> std::ostream& operator<<(std::ostream&, const Test<T>&); template <typename T> class Test { private: T value; public: Test(T value) { this->value = value; } Test() { } const Test<T> operator<<(int shift_bit) const; friend std::ostream& operator<< <T> (std::ostream&, const Test<T>&); }; template <typename T> const Test<T> Test<T>::operator<<(int shift_bit) const { return *this; } template <typename T> std::ostream& operator<<(std::ostream& out, const Test<T>& t) { out << t.value; return out; } int main() { Test<int> v(1234); std::cout << v << std::endl; return 0; } ==== g++ -Wall 編譯訊息 === Test.cpp:23: error: declaration of 'operator<<' as non-function Test.cpp:23: error: expected ';' before '<' token Test.cpp: In function 'std::ostream& operator<<(std::ostream&, const Test<T>&) [with T = int]': Test.cpp:43: instantiated from here Test.cpp:13: error: 'int Test<int>::value' is private Test.cpp:36: error: within this context ==== 問題 ==== 以上的程式碼沒有辦法編譯, 但如果把這兩行 const Test<T> operator<<(int shift_bit) const; friend std::ostream& operator<< <T> (std::ostream&, const Test<T>&); 交換一下順序變成 friend std::ostream& operator<< <T> (std::ostream&, const Test<T>&); const Test<T> operator<<(int shift_bit) const; 就可以編譯得過 想請問一下有經驗的前輩們, 這是 C++ 語法中有規定不能像我原本那種寫法, 還是只是編譯器的問題? -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 114.44.17.186