[問題] 重載運算子與cout<<

看板C_and_CPP (C/C++)作者 (前面右轉)時間13年前 (2013/04/06 11:03), 編輯推噓4(406)
留言10則, 7人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) DEV 問題(Question): matrix<int> A, B; 重載^之後, cout<<(A^B)<<endl; 不行 預期的正確結果(Expected Output): 錯誤結果(Wrong Output): no match for 'operator<<' in 'std::cout << A.matrix<T>::operator^<int>((*(const matrix<int>*)(& B)))' 程式碼(Code):(請善用置底文網頁, 記得排版) 重載^的部分 matrix operator^(const matrix<T> &m1) { matrix<T> m(m1.len); for(int i = 0;i < m1.len;i++) for(int j = 0;j < m1.len;j++) { m[i][j] = 0; for(int k = 0;k < m1.len;k++) m[i][j] = m[i][j] + m1[i][k]*this->mat[k][i]; } return m; } 重載<<的部分 friend ostream &operator<<(ostream &out,matrix<T> &mm) { for(int i = 0;i < mm.len;i++) { for(int j = 0;j < mm.len;j++) out << mm[i][j] << " "; out << endl; } return out; } int main() { matrix<int> A, B; .... cout <<(A^B)<< endl; } 補充說明(Supplement): -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 223.139.169.158 ※ 編輯: heyguys123 來自: 223.139.169.158 (04/06 11:06)

04/06 12:26, , 1F
你沒有overload"<<"
04/06 12:26, 1F

04/06 12:36, , 2F
你的 operator ^ 應該要回傳一個 matrix<T> 才對
04/06 12:36, 2F

04/06 12:37, , 3F
一樓: 他有 overload operator << 啊...
04/06 12:37, 3F

04/06 13:44, , 4F
operator<<的mm加const或去掉&試試?
04/06 13:44, 4F

04/06 14:25, , 5F
我後來照著4樓做對了! 謝謝!
04/06 14:25, 5F

04/06 15:21, , 6F
抱歉
04/06 15:21, 6F

04/06 16:02, , 7F
我覺得應該是opeartor^重載的部分要回傳參考比較正確
04/06 16:02, 7F

04/06 16:38, , 8F
那個不行 因為 m 是那裡面的區域變數 不能回傳其參考
04/06 16:38, 8F

04/06 19:37, , 9F
friend應該要拿掉...?
04/06 19:37, 9F

04/06 23:24, , 10F
矩陣乘法的例子 http://codepad.org/DlfBYYXY
04/06 23:24, 10F
文章代碼(AID): #1HNv1tsm (C_and_CPP)
文章代碼(AID): #1HNv1tsm (C_and_CPP)