作者ric2k1 (Ric)
看板EE_DSnP
標題Re: [問題] operator overloading
時間Sat Dec 15 23:01:26 2007
這... 還沒教吧? (是別班的人問的問題嗎?)
Anyway...
return by object 是 make a copy of the caller's object.
底下 a.xxx().xxx() 會 OK 是因為你沒有用到 caller's data member,
如果有的話, 你事實上第一個 xxx() 與第二個 xxx() 是不同 objects 在呼叫的.
而 operator >> 是要吃兩個 operands, 其中第一個 operand (通常是cin or cout)
是要重複被使用, 所以 return object 的話就無法被重複了...
Anyway, 這個 (member function return by reference) 下個禮拜會講到.
※ 引述《popo4231 (小泰)》之銘言:
: 為什麼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: 59.121.128.162