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

Cd.cpp

#include <iostream>
#include <cctype>
using namespace std;

class Cd{

private:
	char performers[50];
	char label[20];
	int selections;
	double playtime;
public:
	char *perfor(){return performers;};
	char *lab(){return label;};
	int sel(){return selections;};
	double play(){return playtime;};
	//为了Classic的=
	void setPer(char *p){ strcpy(performers,p);};
	void setlab(char *l){strcpy(label,l);};
	void setsel(int num){selections=num;};
	void setplay(double s){playtime=s;};
	//
	Cd(char *s1,char *s2,int n,double x)
	{
		strcpy(performers,s1);
		strcpy(label,s2);
		selections=n;
		playtime=x;
	}
	Cd(const Cd &d)
	{
		strcpy(performers,d.performers);
		strcpy(label,d.label);
		selections=d.selections;
		playtime=d.playtime;
	}
	Cd(){}
	virtual ~Cd(){}//构造函数应为虚函数
	virtual void Report()const
	{
		cout<<"performers:"<<performers<<endl;
		cout<<"label:"<<label<<endl;
		cout<<"selection:"<<selections<<"   playtime:"<<playtime<<endl;
		//cout<<endl;
	}
	virtual Cd&operator=(const Cd &d)
	{
		return Cd(d);
	}
};
class Classic:public  Cd
{
private:
	char mainLabel[50];
public:
	Classic(char *s1,char *s2,char *s3,int n,double x):Cd(s1,s2,n,x)
	{
		strcpy(mainLabel,s3);
	}
	Classic(Classic &c):Cd(c.perfor(),c.lab(),c.sel(),c.play())//不能使用const
	{
		//char *per=c.perfor();
		//strcpy(performers,c.perfor());
		strcpy(mainLabel,c.mainLabel);
	}
	Classic(){}
	virtual ~Classic(){}
	virtual void Report()const
	{
		Cd::Report();//原来是这样子调用父类的方法的啊
		cout<<"mainLabel:"<<mainLabel;
		cout<<endl;
	}
	/*
	Classic &operator=(Classic &c)//不能使用const
	{
		return Classic(c);
	}*/
	void operator=(Classic &c)//不能使用const
	{
		//strcpy(performers,c.perfor());
		Cd::setPer(c.perfor());
		Cd::setlab(c.lab());
		Cd::setsel(c.sel());
		Cd::setplay(c.play());
		strcpy(mainLabel,c.mainLabel);
	}


};

main131.cpp

#include <iostream>
#include "Cd.cpp"
using namespace std;
void Bravo(const Cd &d)
{
	d.Report();
};
void main131()
{
	Cd c1("Beates","Capitol",14,35.5);
	Classic c2=Classic("Piano Sonata in B flag,Fantasia in C","Alfred Brendel","Philips",2,57.17);
	Cd *pcd=&c1;

	cout<<"Using object directly:"<<endl;
	c1.Report();
	cout<<endl;
	c2.Report();

	cout<<"Using type cd * pointer to object:"<<endl;
	pcd->Report();
	cout<<endl;
	pcd=&c2;//重定位pcd
	pcd->Report();

	cout<<"Calling a funciton with a Cd reference argument:"<<endl;

	Bravo(c1);
	Bravo(c2);

	cout<<"Testing assignment:"<<endl;
	//Classic copy=c2;//这样也是可以的
	//Classic copy(c2);//这样就没问题,那就是赋值出了问题
	Classic copy; //因为这里已经初始化了,所以copy已经是利用Classic()初始化了
	copy=c2;//这里有问题、//这样的话,这样赋值就不能返回一个Classic的值了
	copy.Report();
	cin.get();
	


}


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值