您的位置:首页 > 编程语言 > C语言/C++

C++primer plus第六版课后编程练习答案13.4

2015-12-03 17:25 525 查看
#include <iostream>
#include <string>
//我懒得用char*了
using namespace std;
class Port{
protected:  //懒得用方法了,就直接保护吧
string brand;
//string style;//不需要style,因为派生出来的就是style
int bottles;
public:
string getbr()const{return brand;};
int getbot()const{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,这种情况,必须声明的同时赋值
if(this==&p)
return *this;
brand=p.brand;
bottles=p.bottles;
return *this;
}
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)
{
brand=vp.brand;
//style=p.style;
bottles=vp.bottles;
nickname=vp.nickname;
year=vp.year;
}
~VintagePort(){};
VintagePort &operator=(const VintagePort &vp)
{
// return VintagePort(vp);   //使用这种方法调用的是使用此赋值运算符的构造函数,当此对象构造过后,此赋值运算符将无效
if(this==&vp)
return *this;
brand=vp.brand;
bottles=vp.bottles;
nickname=vp.nickname;
year=vp.year;
return *this;
}
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;
}
};
#include <iostream>
#include "Port.cpp"
using namespace std;

void main()
{
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);
// VintagePort vp3("Vin",14,"xo",19);
vp3.Show();
//	VintagePort vp3;
//vp3=vp2;
vp3.Show();

cin.get();
cin.get();

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: