Port.cpp
#include
#include
//老规矩,我懒得用char*了
using namespace std;
class Port{
private:
string brand;
//string style;//不需要style,因为派生出来的就是style
int bottles;
public:
string br(){return brand;};
int bot(){return bottles;};
Port(const string br=”none”,int b=0)//const string st=”none”
{
brand=br;
//style=st;
bottles=b;
}
Port(const Port &p)
{
brand=p.brand;
//style=p.style;
bottles=p.bottles;
}
//Port(){};//因为派生类无参数的构造函数,所以基类必须有相对应的构造函数
//发现不用也是可以的,因为第一个有了默认参数值,也可以算是无参构造函数
virtual ~Port(){}
Port &operator=(const Port &p)
{
return Port(p);//不能使用类似:Port p;p=p2,这种情况,必须声明的同时赋值
}
Port &operator+=(int b)
{
bottles=bottles+b;
return *this;
}
Port &operator-=(int b)
{
if(bottles>=b)
bottles=bottles-b;
else
cout<<”error!no so much brand!”<<endl;
return *this;
}
int BottlesCount()const{return bottles;};
virtual void Show()const
{
cout<<”Brand:”<<brand<<endl;
//cout<<”Kind:”<<style<<endl;
cout<<”Bottlse:”<<bottles<<endl;
}
friend ostream &operator<<(ostream &os,const Port &p)
{
cout<<p.brand<<” ,”<<p.bottles<<endl;
return os;
}
};
class VintagePort:public Port
{
private:
string nickname;
int year;
public:
VintagePort(){
Port::Port();
nickname=”default”;
year=2999;
};
VintagePort(const string br,int b,const string nn,int y=2999):Port(br,b)
{
nickname=nn;
year=y;
};
VintagePort(const VintagePort &vp)
{
Port::Port(vp);//这样是否可以?,答案是不可以
//brand=vp.br();
nickname=vp.nickname;
year=vp.year;
}
~VintagePort(){};
VintagePort&operator=(const VintagePort &vp)
{
return VintagePort(vp);
}
void Show()
{
Port::Show();
cout<<”nickname:”<<nickname<<endl;
cout<<”year:”<<year<<endl;
}
friend ostream &operator<<(ostream &os,const VintagePort &p)
{
os<<(const Port &)p;
cout<<p.nickname<<” ,”<<p.year<<endl;
return os;
}
};
main134.cpp
#include
#include “Port.cpp”
using namespace std;
void main134()
{
/*Port p1;
Port p1(“Gallo”,20);
Port p2(p1);
Port p3;//=p1;
//p3=p1;//这时候,p3已经采取了默认初始化值
//p1.Show();
//cout<<p1;
//cout<<p3;
/*
p2.Show();
p2+=10;
p2.Show();
p2-=15;
p2.Show();
*/
VintagePort vp1;
//vp1.Show();
VintagePort vp2(“Vintage”,140,”xxoo”,1989);
//vp2.Show();
cout<<vp2;
//VintagePort vp3(vp2);//这样子的话,brand,bottles都是Port初始化默认值
VintagePort vp3=vp2;//这里我就不改了,自己改一下吧,最近有点累
vp3.Show();
cin.get();
cin.get();
}
—————————————————————————————————————————————————— //写的错误或者不好的地方请多多指导,可以在下面留言或者给我发邮件,指出我的错误以及不足,以便我修改,更好的分享给大家,谢谢。 转载请注明出处:https://www.royalchen.com/ author:royalchen Email:royalchen@royalchen.com ———————————————————————————————————————————————————
- 本文作者: royalchen
- 本文链接: http://www.royalchen.com/2016/02/24/cprimerplus第六版课后编程题答案134/
- 版权声明: 本博客所有文章除特别声明外,均采用 MIT 许可协议。转载请注明出处!