作者conan77420 (小马非马)
看板C_and_CPP
标题[问题]关於 overload的问题
时间Sat May 9 21:50:14 2009
程式:
#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
1F:推 legendmtg:ostream 05/09 22:01
2F:推 ryancid:+= 05/09 22:06
3F:→ conan77420:问题好像不是+=耶...只改ostream好像也不对0.0 05/10 13:34