簡體   English   中英

復制構造函數,子類

[英]Copy Constructors, Child Classes

一些幫助檢查我的代碼的正確性。

事實上,我正在使用來自母親 class 的復制構造函數復制子 object,對嗎? 或者,我是否應該為孩子實現一個復制構造函數?

#include <iostream>
class Mother{

    public:

     Mother(int data):member(data){
     }

     Mother(Mother const& mother):member(mother.member){

     }

     Mother& operator=(Mother const& mother){

        if(this != &mother){
            member=mother.member;
        }

     }

     ~Mother(){
     }

     friend std::ostream& operator<<(std::ostream& out, Mother const& mother){
         out<<"Data :"<<mother.member<<std::endl;
         return out;
     }

    protected:

        int member;
};

class Child : public Mother{
   public:
       Child(int data):Mother(data){
       }
       ~Child(){
       }

   private:
    std::string chData;

};

int main()
{
    int a(42);
    Child child(a);
    Child copyChild = Child(a);

    std::cout<<copyChild;

    return 0;
}

非常感謝。

實際上,您正在使用子 class 的 CopyConstructor。 即使您沒有聲明它,它也會在編譯代碼時隱式創建。

暫無
暫無

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

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