[問題]關於 overload的問題
程式:
#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
05/09 22:01, 1F
推
05/09 22:06, , 2F
05/09 22:06, 2F
→
05/10 13:34, , 3F
05/10 13:34, 3F
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 1 之 2 篇):
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章