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


 

Port.cpp

#include <iostream>
#include <string>
//老规矩,我懒得用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 <iostream>
#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();


}

 

 


发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注