[問題]關於 overload的問題

看板C_and_CPP (C/C++)作者 (小馬非馬)時間16年前 (2009/05/09 21:50), 編輯推噓2(201)
留言3則, 3人參與, 最新討論串1/2 (看更多)
程式: #include<iostream> #include<stdio.h> using namespace::std; class box { public: box(); box(int l); box(int w,int h,int d); box operator+(const box &b) { box temp; temp.w=w+b.w; temp.h=h+b.h; temp.d=d+b.d; return temp; } int w,h,d; }; box::box() { w=1; h=1; d=1; } box::box(int l) { w=l; h=l; d=l; } box::box(int w,int h,int d) { this->w=w; this->h=h; this->d=d; } int main() { box b1; box b2(2); box b3(1,2,3); b1=b2+b3; cout<<b1.w<<b1.h<<b1.d<<" "<<b2.w<<b2.h<<b2.d<<" "<<b3.w<<b3.h<<b3.d<<" "<<endl; system("pause"); } =========================== 以爬文,小弟第一次接觸overload,不能做的原因不是很懂,如果問題太笨請多包含~ 1.是用dve。為什麼在class中的int w,h,d;前如果加上private會編譯不過? 不是在不同class的時候private才會不能存取嗎?〈好吧我承認這跟overload沒關 /_\〉 2.如果把class中的operator+(const box &b)拉出來 寫成:box::box operator+(const box &b) { box temp; temp.w=w+b.w; temp.h=h+b.h; temp.d=d+b.d; return temp; } 為什麼編譯會不過呢? 3.如果要做cout的overload,副程式的類別是要用ofstream嗎? 就是寫成像這樣:ofstream operator<<(ofstream &out,box &b) 不過編譯沒過,請問該怎麼修正? 謝謝! -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 61.229.128.82

05/09 22:01, , 1F
ostream
05/09 22:01, 1F

05/09 22:06, , 2F
+=
05/09 22:06, 2F

05/10 13:34, , 3F
問題好像不是+=耶...只改ostream好像也不對0.0
05/10 13:34, 3F
文章代碼(AID): #1A1OePhz (C_and_CPP)
討論串 (同標題文章)
文章代碼(AID): #1A1OePhz (C_and_CPP)