[問題] template與operator合用的新手問題

看板C_and_CPP作者 (全脂鮮乳)時間14年前 (2011/04/07 09:55), 編輯推噓2(202)
留言4則, 2人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) vc++ 6.0 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) no 問題(Question): template與operator合用時出現了型別不明? 餵入的資料(Input): no 預期的正確結果(Expected Output): 印出 5 錯誤結果(Wrong Output): --------------------Configuration: Text - Win32 Debug-------------------- Compiling... Text.CPP D:\Codes\C&C++\複製 -0\Text.CPP(30) : error C2679: binary '=' : no operator defined which takes a right-hand operand of type 'class obj1<int>' (or there is no acceptable conversion) Error executing cl.exe. Text.obj - 1 error(s), 0 warning(s) 程式碼(Code):(請善用置底文網頁, 記得排版) #include < iostream > using namespace std ; template < class Type > class obj1 { public : Type status ; obj1 ( Type reg ) : status ( reg ) {} } ; template < class Type > class obj2 { public : Type status ; obj2 & operator= ( const obj1 & o1 ) { status = o1.status ; return *this ; } } ; int main ( ) { obj1 < int > ob1 ( 5 ) ; obj2 < int > ob2 ; ob2 = ob1 ; cout << ob2.status << endl ; system ( "pause" ) ; return 0 ; } 補充說明(Supplement): 在個別練習template和operator時都還ok 結果合用時就出現型別定義不明的問題 新手菜逼巴的還請各位大大見諒。 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 223.138.116.235

04/07 10:24, , 1F
因為你的 obj2.operator= 吃的參數是 const obj1 &
04/07 10:24, 1F

04/07 10:24, , 2F
而不是 const obj1<T> &
04/07 10:24, 2F

04/07 10:26, , 3F
啊 你是 <class Type> 總之我的意思就是這樣...
04/07 10:26, 3F

04/07 10:44, , 4F
哇!謝謝你!不然一直不知道要怎麼改!
04/07 10:44, 4F
文章代碼(AID): #1DdHcLiG (C_and_CPP)