c++primer plus 第13章 编程题第1题

  在第1题里面,因为两个类的成员都自己开辟了数组空间,所以使用默认的复制构造函数和重载赋值运算符就好。

  析构函数一定要写成虚函数

  顺便提一提复习题第3题:在重载运算符里,返回引用和返回对象有什么区别?返回对象并不会报错,但是效率会比返回引用低

#pragma once
#ifndef CD_H_
#define CD_H_
//base class

class Cd
{
private:
    char performers[50];
    char label[20];
    int selection;    //number of selection
    double playtime;
public:
    Cd();
    //Cd(const Cd & d);
    Cd(char * s1, char * s2, int n, double x);
    virtual ~Cd();
    void Report() const;    //reports all cd data
    //Cd & operator= (const Cd & d);
};
#endif // !CD_H_
Cd.h
#pragma once
#ifndef CLASSIC_H_
#define CLASSIC_H_
#include"CD.h"

class Classic : public Cd
{
private:
    char mainprod[20];
public:
    
    Classic();
    Classic(char * s1, char * s2, char * s3, int n, double x);
    //Classic(const Classic & a);
    ~Classic();
    //Classic & operator=(const Classic & a);
    void Report() const;
};

#endif // !CLASSIC_H_
classic.h
#include"classic.h"
#include<cstring>
#include<iostream>
using std::strcpy;
using std::cout;
using std::endl;
//base cd

Cd::Cd()
{
    performers[0] = '\0';
    label[0] = '\0';
    selection = 0;
    playtime = 0.0;
}

Cd::Cd(char * s1, char * s2, int n, double x)
{
    strcpy(performers, s1);
    strcpy(label, s2);
    selection = n;
    playtime = x;
}

Cd::~Cd()
{

}

void Cd::Report() const
{
    cout << "performers: " << performers << endl;
    cout << " label: " << label << endl;
    cout << " selection: " << selection << endl;
    cout << " playtime: " << playtime << endl;
}

Classic::~Classic()
{

}

Classic::Classic() : Cd()
{
    mainprod[0] = '\0';    //构造函数要统一型式以兼容析构函数
}

Classic::Classic(char * s1, char * s2, char * s3, int a, double x) : Cd(s1, s2, a, x)
{
    strcpy(mainprod, s3);
}

void Classic::Report() const
{
    Cd::Report();
    cout << " mainproduction: " << mainprod << endl;
}
methods.cpp
#include<iostream>
using namespace std;
#include"classic.h"    //will contain #include cd.h
void Bravo(const Cd & disk);
//记住要自己修改cd.h文件
int main()
{
    Cd c1("Beatles", "Capitol", 14, 35.5);
    Classic  c2 = Classic("Piano Sonata in B flat, Fantasia in C", "Alfred Brendel", "Philios", 2, 57.17);

    Cd * pcd = &c1;

    cout << "using object directly:\n";
    c1.Report();
    c2.Report();

    cout << "using type cd * pointer to object:\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();
}
test.cpp

猜你喜欢

转载自www.cnblogs.com/syne-cllf/p/9266355.html