作者popo4231 (小泰)
看板EE_DSnP
標題[問題] operator overloading
時間Sat Dec 15 22:27:24 2007
為什麼operator overloading函式一定要回傳ostream&
回傳ostream會compile error
可是在cascading call的時候就不會有這種情形發生
請問問題是出在哪邊?
code:
#include<iostream>
#include<iomanip>
using namespace std;
class student
{
friend istream operator>>(istream&,student&);
friend ostream operator<<(ostream&,student&);
private:
int num;
char ch;
string str;
};
istream operator>>(istream& input,student& stu)
{
input>>setw(2)>>stu.num;
input.ignore(1);
input>>setw(1)>>stu.ch;
input.ignore(3);
input>>setw(10)>>stu.str;
return input;
}
ostream operator<<(ostream& output,student& stu)
{
output<<stu.num<<' '<<stu.ch<<" "<<stu.str<<endl;
return output;
}
int main()
{
student S;
cin>>S;
cout<<S;
system("pause");
return 0;
}
只要把回傳型態改成reference就可以過了
但是cascading就可以回傳object而不用回傳reference
code:
#include<iostream>
using namespace std;
class A
{
public:
A xxx(void)
{
cout<<"xd囧"<<endl;
return (*this);
}
};
int main()
{
A a;
a.xxx().xxx();
system("pause");
}
為什麼會這樣呢?
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.112.241.177