派生类的拷贝构造【C++继承】
生活随笔
收集整理的這篇文章主要介紹了
派生类的拷贝构造【C++继承】
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
- 語法
- 拷貝構造順序
- 圖示
- 說明
- 拷貝構造順序
- 拷貝構造實例
語法
派生類::派生類(const 派生類& another):基類(another),派生類新成員(another.新成員) {//派生類新成員(another.新成員) }拷貝構造順序
圖示
說明
父類中,一部分成員需要拷貝構造來完成。
子類中,也有一部成員需要拷貝構造來完成。
子類中的內嵌子對象也需要拷貝構造來完成。
拷貝構造順序
代碼演示:
#include <iostream>using namespace std;class A { public:A() {cout << "A()" << endl;}A(const A& anthter){cout << "A(const A & anthter)" << endl;} };class C { public:C(){cout << "C()" << endl;}C(const C& another){cout << "C(const c & another)" << endl;} };class B :public A { public:B(){cout << "B()" << endl;}B(const B& another):A(another), _c(another._c){cout << "B(const B& another):A(another), _c(another._c)" << endl;}C _c; }; int main() {B b;cout << "+++++++++++++++" << endl;B bb(b);return 0; }運行結果:
拷貝構造實例
代碼演示:
#include <iostream>using namespace std;class Student { public:Student(string name, int num, char sex):_name(name), _num(num), _sex(sex) {}void dump(){cout << "name:" << _name << endl;cout << "num :" << _num << endl;cout << "sex :" << _sex << endl;}Student(const Student& another){this->_name = another._name;this->_num = another._num;this->_sex = another._sex;}private:string _name;int _num;char _sex; };class Birthday { public:Birthday(int y, int m, int d):_year(y), _month(m), _day(d){}void disBirthday(){cout << "birth date:" << _year << ":" << _month << ":" << _day << endl;}Birthday(const Birthday& another){this->_year = another._year;this->_month = another._month;this->_day = another._day;}private:int _year;int _month;int _day; };class Graduate :public Student { public:Graduate(string name, int num, char sex, float salary, int y, int m, int d):Student(name, num, sex), birth(y, m, d), _salary(salary) {}Graduate(const Graduate& another):Student(another), birth(another.birth) //顯示調用拷貝構造{_salary = another._salary;}void dis(){dump();cout << "salary:" << _salary << endl;birth.disBirthday();}private:float _salary;Birthday birth; };class Doctor :public Graduate { public:Doctor(string name, int num, char sex,float salary, int y, int m, int d, string t):Graduate(name, num, sex, salary, y, m, d), title(t){}Doctor(const Doctor & another):Graduate(another) //顯示調用拷貝構造{this->title = another.title;}void disDoctor(){dis();cout << "title:" << title << endl;}private:string title; };int main() {Doctor d("sun", 2001, 's', 10000, 1990, 9, 19,"Doctor d");d.disDoctor();Doctor dd(d);dd.disDoctor();return 0; }運行結果:
總結
以上是生活随笔為你收集整理的派生类的拷贝构造【C++继承】的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 派生类的构造【C++继承】
- 下一篇: C++Primer Plus (第六版)