1. 以下面的类声明为基础:
class Cd {
private:
char performers[50];
char label[20];
int selections;
double playtime;
public:
Cd(char* s1, char* s2, int n, double x);
Cd(const Cd& d);
Cd();
~Cd();
void Report() const; // 显示此CD信息
Cd& operator=(const Cd& d);
};
派生出一个Classic类,并添加一组char成员,用于存储指出CD中主要作品的字符串。修改上述声明,使基类的所有函数都是虚的。如果上述定义声明的某个方法并不需要,则请删除它。使用下面的程序测试您的产品:
#include <iostream>
#include "classic.h"
using namespace std;
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", "Philips", 2, 57.17, "Alfred Brendel");Cd* pcd = &c1;
cout << "Using object directly:\n";
c1.Report();
c2.Report();cout << "Using type cd* pointer to objects:\n";
pcd->Report();
pcd = &c2;
pcd->Report();cout << "Calling a function with a Cd reference argument:\n";
Bravo(c1);
Bravo(c2);cout << "Testing assignment: ";
Classic copy;
copy = c2;
copy.Report();return 0;
}void Bravo(const Cd& disk) {
disk.Report();
}
解答:
#pragma once
// classic.h
#ifndef CLASSIC_H_
#define CLASSIC_H_
class Cd {
private:
char performers[50];
char label[20];
int selections;
double playtime;
public:
Cd(const char* s1, const char* s2, int n, double x);
// Cd(const Cd& d);
Cd();
// virtual ~Cd();
virtual void Report() const; // 显示此CD信息
// Cd& operator=(const Cd& d);
};
class Classic : public Cd {
private:
char primary_work[50];
public:
Classic(const char* s1, const char* s2, int n, double x, const char* s3);
Classic();
virtual void Report() const;
// virtual ~Classic();
};
#endif // !CLASSIC_H_
// cd.cpp
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstring>
#include "classic.h"
using std::strncpy;
using std::strcpy;
using std::cout;
using std::endl;
Cd::Cd(const char* s1, const char* s2, int n, double x) {
strncpy(performers, s1, 49);
performers[49] = '\0';
strncpy(label, s2, 19);
label[19] = '\0';
selections = n;
playtime = x;
}
Cd::Cd() {
strcpy(performers, "None");
strcpy(label, "No label");
selections = 0;
playtime = 0.0;
}
void Cd::Report() const {
cout << "Performers: " << performers << endl;
cout << "Label: " << label << endl;
cout << "Selections: " << selections << endl;
cout << "Playtime: " << playtime << endl;
}
Classic::Classic(const char* s1, const char* s2, int n, double x, const char* s3): Cd(s1, s2, n, x) {
strncpy(primary_work, s3, 49);
primary_work[49] = '\0';
}
Classic::Classic(): Cd() {
strcpy(primary_work, "None");
}
void Classic::Report() const {
Cd::Report();
cout << "Primary work: " << primary_work << endl;
}
// 13-1
#include <iostream>
#include "classic.h"
using namespace std;
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", "Philips", 2, 57.17, "Alfred Brendel");
Cd* pcd = &c1;
cout << "Using obje