1. 程式人生 > >各種錯誤(C++)

各種錯誤(C++)

OS X EI Capitan [10.11.6]
Xcode [8.0]

C++

程式碼:

#include<iostream>

#include<math.h>

#include"MyComplex.h"

usingnamespacestd;

int main(int argc,constchar * argv[]) {

// insert code here...

MyComplex c1;

MyComplex c2;

cin >> c1;

    c2 = c1;

cout << c1 <<endl;

cout << c2 <<endl;

MyComplex

c3;

    c3 = c1+c2;//error1:No viable overloaded '='

    cout << c1+c2 << Lendl;//error2: No matching constructor for initialization of 'MyComplex'

    cout << c1-c2 << Lendl;//error

    cout << c1/c2 << Lendl;//error

    cout << c1*c2 << Lendl;//error

return0;

}

那麼對於=的過載是如何定義的呢?請看程式碼。

MyComplex&operator = (MyComplex &rhs){

real = rhs.getReal();

imaginary = rhs.getImaginary();

return *this;

    }

看起來並沒有什麼問題。通過查閱 http://www.cplusplus.com/forum/general/153830/ 找到了錯誤原因:

Peter87大神說:A temporary object can't bind to a non-const reference. 

(臨時物件不能與非常量引用繫結,也就是說,繫結的引用必須是常量)

因此,過載=函式的形參必須是const。(如此隱蔽的錯誤真是欲哭無淚。。。)

加了const後error1消失:

MyComplex&operator = (constMyComplex &rhs){

real = rhs.getReal();

imaginary = rhs.getImaginary();

return *this;

    }

error2也是同樣的錯誤原因。

friend ostream&operator<<(ostream& os,const MyComplex &c);

const是非常重要的!要的!的!!!

改完後error都消失了