派生类复制构造函数如何复制基类的私有数据成员(c++)

 
 

//
// Created by lenovo on 2018/5/12.
//

#ifndef PROJECT_1_CLASSIC_H
#define PROJECT_1_CLASSIC_H

#include <cstring>
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();
    virtual void report() const;
    cd& operator=(const cd& d);
};

class classic:public cd{
private:
    char projectname[50];
public:
    classic(char*s3,char*s2,char*s1,int n,double x):cd(s1,s2,n,x){strcpy(projectname,s3);}
    classic(const classic& cs);
    classic();
    ~classic();
    void report()const;
    classic&operator=(const classic& cs);
};
#endif //PROJECT_1_CLASSIC_H


//
// Created by lenovo on 2018/5/12.
//
#include <iostream>
#include "classic.h"
using namespace std;

cd::cd(char *s1, char *s2, int n, double x) {
    performers=s1;
    label=s2;
    selections=n;
    playtime=x;
}

cd::cd(const cd &d) {
    performers=d.performers;
    label=d.label;
    selections=d.selections;
    playtime=d.playtime;
}

cd::cd() {}

cd::~cd() {}

void cd::report() const {
    cout<<"performers: "<<performers<<endl;
    cout<<"labels: "<<label<<endl;
    cout<<"selections"<<selections<<endl;
    cout<<"playtime"<<playtime<<endl;
}

cd& cd::operator=(const cd &d) {
    performers=d.performers;
    label=d.label;
    selections=d.selections;
    playtime=d.playtime;
    return *this;
}

classic::classic(const classic &cs) {           //直接调用基类复制构造函数即可
    projectname=cs.projectname;
    cd::cd(cs);
}

void classic::report() const {
    cd::report();
    cout<<"song_list: "<<projectname;
}

classic& classic::operator=(const classic &cs) {     //运算符重载在文件中的定义
    projectname=cs.projectname;
    cd::operator=(cs);
}


#include <iostream>
#include "classic.h"
void bravo(const cd& disk);
using namespace std;

int main() {
   cd c1("beatles","capitol",14,35.5);
   classic c2=classic("piano sonata in b flat,pantasia in c",
           "alfred brendel","philips",2,57.17);
   cd*pcd=&c1;
   cout<<"using objective directively:\n";
   c1.report();
   c2.report();
   cout<<"using type cd* pointer to objectives:\n";
   bravo(c1);
   bravo(c2);
   cout<<"tesing assignment: ";
   classic copy;
   copy=c2;
   copy.report();

   return 0;
}

void bravo(const cd& disk){
    disk.report();
}

猜你喜欢

转载自blog.csdn.net/billy1900/article/details/80288465
今日推荐