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,这里主要考察虚函数的使用。