首页 > 解决方案 > 复制构造函数,子类

问题描述

一些帮助检查我的代码的正确性。

我正在使用来自 Mother 类的 Copy Constructor 复制 Child 对象,这是正确的吗?或者,我是否应该为 Child 实现一个复制构造函数?

#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;
}

非常感谢。

标签: c++oopconstructorcopy

解决方案


实际上,您正在使用子类的 CopyConstructor。即使您没有声明它,它也会在编译代码时隐式创建。


推荐阅读