簡體   English   中英

c++ - 是否可以在引用另一個派生 class 的派生 class 中聲明復制構造函數?

[英]c++ - Is it possible to declare a copy constructor in a derived class that references another derived class?

例如,如果我創建一個Base class 和 2 個派生類DerivedOneDerivedTwo ,是否可以在DerivedOne中聲明一個引用DerivedTwo的復制構造函數?

謝謝

你在尋找這樣的東西嗎?

#include <iostream>
using namespace std;

class B{
    protected:
        int a;
    public:
        B(int i):a(i){}
        B(const B &b): a(b.a){cout<<"copying... ";}   //base class copy constructor
        virtual void print()=0;
};

class D1: public B{
    //other functions and variables
    public:
        D1(): B(5){ /*other initializations*/ };
        void print(){cout<<"D1:"<<a<<endl;}
};

class D2: public B{
    //other functions and variables
    public:
        D2(const B &b):B(b){ /*other initializations*/ }    //COPY CONSTRUCTOR
        void print(){cout<<"D2:"<<a<<endl;}
};

int main() {
    D1 d1;
    d1.print();     // output: D1:5

    B &b=d1;
    D2 d2(b);
    d2.print();     // output: copying... D2:5

    return 0;
}

如果有不清楚的地方,請在評論中告訴我。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM