作者satokuzao (no元)
看板C_and_CPP
標題[問題] >>過載與class裡的private之問題!
時間Tue Apr 21 21:07:42 2009
設立一個數學的虛實數物件(object),例如:0+0i(預設)
目的:輸入實部和虛部的數字並輸出,例如:輸入1 +2i則輸出1+2i
問題:目前輸入1 2後依舊跑出預設(已解決)
紅色字為修正部分
#include<iostream>
#include <cstdlib>
using namespace std;
class Complex
{
private:
double real,imag;
public:
Complex::Complex():real(0),imag(0){};
void input(int a,int b);
double getRe() ;
double getIm() ;
friend istream& operator >>(istream& inStr,Complex
& recive);
friend ostream& operator <<(ostream& ouStr,Complex
& recive);
void input(double a,double b);
};
void Complex::input(double a,double b)
{
real=a;
imag=b;
}
istream& operator >>(istream& inStr,Complex
& recive)
{
cout<<"請輸入實數及虛數部分\n";
double a,b;
inStr>>a>>b;
recive.input(a,b);
return inStr;
}
int main()
{
Complex test;
cin>>test;
cout<<"現在輸出TEST輸入結果:"<<test<<endl;
system("pause");
}
ostream& operator <<(ostream& ouStr,Complex
& recive)
{
cout<<"輸出結果為";
ouStr<<recive.getRe();
cout<<"+";
ouStr<<recive.getIm();
cout<<endl;
}
double Complex::getIm()
{ return imag; }
double Complex::getRe()
{ return real; }
※ 編輯: satokuzao 來自: 140.117.181.63 (04/21 22:13)
1F:→ james732:Complex recive 改成 Complex &recive 的話? 04/21 22:13
2F:→ satokuzao:糟糕!秒殺~沒錯加入&參照就OK了 04/21 22:15
※ 編輯: satokuzao 來自: 140.117.181.63 (04/21 22:20)
3F:→ satokuzao:想起來了<<與>>的運算子過載是屬於參照類型!哀小細節.. 04/21 22:21