1.
cd.h
#ifndef cd_H_
#define cd_H_
#include<string>
#include <iostream>
#include <cstring>
using std::cout;
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() {
}
virtual~Cd() {
}
virtual void Report() const;
};
class Classic :public Cd
{
private:
char works[50];
public:
Classic(const char * s1, const char *s2, const char * s3, int n, double x);
Classic() :Cd() {
}
virtual void Report() const;
};
Cd::Cd(const char * s1, const char * s2, int n, double x)
{
strncpy_s(performers, s1, 50);
performers[49] = '\0';
strncpy_s(label, s2, 20);
label[19] = '\0';
selections = n;
playtime = x;
}
void Cd::Report() const
{
cout << "performers: " << performers << '\n';
cout << "label: " << label << '\n';
cout << "selections: " << selections << '\n';
cout << "playtime: " << playtime << '\n';
}
Classic::Classic(const char * s1, const char *s2, const char * s3, int n, double x) :Cd(s2, s3, n, x)
{
strncpy_s(works, s1, 50);
works[49] = '\0';
}
void Classic::Report() const
{
cout << "works: " << works << '\n';
Cd::Report();
}
#endif
main.cpp
#include "cd.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",
"Alfred Brendel", "Philips", 2, 57.17);
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();
}
2.
main.cpp和上一题一样的
#ifndef cd_H_
#define cd_H_
#include <iostream>
#include<string>
using std::cout;
class Cd {
private:
char *performers;
char *label;
int selections;
double playtime;
public:
Cd(const char * s1, const char * s2, int n, double x);
Cd();
virtual~Cd();
virtual void Report() const;
Cd & operator=(const Cd & d);
};
class Classic :public Cd
{
private:
char *works;
public:
Classic(const char * s1, const char *s2, const char * s3, int n, double x);
Classic();
~Classic();
virtual void Report() const;
Classic & operator=(const Classic & c);
};
Cd::Cd()
{
performers = nullptr;
label = nullptr