#include<iostream.h>// c++6.0不支持把成員函數重載為友元函數,,所以用帶。h的庫 class Complex { int real; int imag; public: Complex(int a,int b):real(a),imag(b){} Complex(){}; Complex(int a){real=a;imag=0;} void display(); friend Complex operator +(Complex &c1,Complex &c2); }; Complex operator+(Complex&c1,Complex&c2) { return Complex(c1.real+c2.real,c1.imag+c2.imag);//注意返回帶Cmplex } void Complex::display() { cout<<real<<'+'<<imag<<'i'<<endl; } int main() { Complex c1(1,5),c2(3,7),c3;int a=2; c3=c1+a; cout<<"c3="<<endl; c3.display(); return 0; } 我已經定義了轉換構造函數,為什么c1+a會出錯 為什么在complex&c1,Complex&c2)中加const就沒問題啦求大神求解決,謝謝啦! {
3 回答

慕運維8079593
TA貢獻1876條經驗 獲得超5個贊
c3 = c1 + Complex(a);這樣就行了吧,你的構造沒有定義復數與int相加
再說的+運算符重載這樣寫不就行了
Complex operator+(Complex&c1)
{
return Complex(c1.real + real, c1.imag + imag);
};

臨摹微笑
TA貢獻1982條經驗 獲得超2個贊
這個問題挺有意思。
我認為形參不加const,將調用形參的拷貝構造函數先復制一個對象出來,而Complex類沒有拷貝構造函數也不會接受int型的參數,所以編譯報錯。
加const后,函數不會復制實參,在調試過程中發現調用了Complex(int a)這個構造函數,我猜想可能編譯器在這個時候做了個隱含的類型轉換吧,c3=c1+a;估計就變成了c3=c1+(Complex)a;
添加回答
舉報
0/150
提交
取消