C++PrimerPlus:第十三章类和继承:编程练习1

C++PrimerPlus:第十三章类和继承:编程练习1

提示:这里可以添加系列文章的所有文章的目录,目录需要自己手动添加
例如:编程练习1


提示:写完文章后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

提示:这里可以添加本文要记录的大概内容:

这里把整个写在一个cpp文件中
派生出一个 Classic 类,并添加一组 char 成员,用于存储指出 CD 中主要作品的字符串。修改上述声明,使基类的所有函数都是虚的。如果上述定义声明的某个方法并不需要,则请删除它。使用下面的程序测试您的产品:


提示:以下是本篇文章正文内容,下面案例可供参考

一、题

#define _CRT_SECURE_NO_WARNINGS
	#include<iostream>
	using namespace std;
	

//base class
	class Cd	//represents a CD disk
	{
	private:
		char performers[50];//主演
		char label[20];//篇名
		int selections;	//number of selections
		double playtime;//playing time in minutes
	public:
		Cd(const char* s1, const char* s2, int n, double x);
		Cd(const Cd& d);
		//Cd();
		~Cd() {};
		virtual void Report()const;//reports all CD data
		//Cd& operator=(const Cd& d);
	};
	//derive
	class Classic :public Cd
	{
	private:
		static const unsigned mk_size = 64;
	private:
		char m_songs[mk_size];
	public:
		Classic(const char* songsList = "", const char* s1 = "", const char* s2 = "",
			int n = 0, double x = 0.0);
		virtual void Report()const;
	};
	static void
		copyStr(char* pDes, const char* pSrc, unsigned desLen)
	{
		unsigned strLen = strlen(pSrc) < desLen - 1 ? strlen(pSrc) : desLen - 1;
		strncpy(pDes, pSrc, strLen);
		pDes[strLen] = '\0';

	}
	Cd::Cd(const char* s1, const char* s2, int n, double x)
		:selections(n),playtime(x)
	{
		copyStr(performers, s1, 50);
		copyStr(label, s2, 20);
	}
	void 
		Cd::Report()const
	{
		cout << performers << ", " << label << ", " << selections << ", " << playtime;
	}

	// Classic 
	Classic::Classic(const char* songsList,
		const char* s1, const char* s2, int n, double x)
		:Cd(s1, s2, n, x)
	{
		copyStr(m_songs, songsList, mk_size);
	}
	void
		Classic::Report()const
	{
		Cd::Report();
		cout << ", " << m_songs << endl;
	}
	
	void Bravo(const Cd& disk);
int main()
{
	Cd c1("Beatles", "Capitol", 14, 35.5);
	Classic c2 = Classic("Piano Sonata in B flat,Fantasia in c",
		"Alfred Brendel", "philips", 2, 57.17);
	Cd* pcd = &c1;
	cout << endl;


	cout << "Using object directly:\n";
	c1.Report();//use Cd method
	c2.Report();//use Classic method
	cout << endl;

	cout << "Using object directly:\n";
	pcd->Report();//use cd method for cd object
	pcd = &c2;
	pcd->Report();//use classic method ofr classic object
	Bravo(c1);
	Bravo(c2);
	cout << endl;

	cout << "Testing assignment: ";
	Classic copy;
	copy = c2;
	copy.Report();

	return 0;
}
void Bravo(const Cd& disk)
{
	disk.Report();
}

总结

提示:这里对文章进行总结:

1,这里主要考察虚函数的使用。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值