【问题标题】:can you help me with the copy c'tor for derived class?你能帮我复制派生类的c'tor吗?
【发布时间】:2022-01-05 06:06:42
【问题描述】:

我有这个基类:

class LevelPlayer
{
protected:
   int level;
   int id;
public:
    LevelPlayer():id(-1){}
    LevelPlayer(int level,int id):level(level),id(id){}
    virtual ~LevelPlayer()=default;
    LevelPlayer(const LevelPlayer&)=default;
    LevelPlayer&  operator=(const LevelPlayer&)=default;
};

还有这个派生类:

class GroupPlayer: public LevelPlayer
{
private:
    IdPlayer* ptr;
public:
    GroupPlayer():LevelPlayer(),ptr(nullptr){}
    GroupPlayer(int level,int id,IdPlayer* ptr):LevelPlayer(level,id),ptr(new IdPlayer(*ptr)){}
    ~GroupPlayer()override=default;
    GroupPlayer(const GroupPlayer&);
    GroupPlayer&  operator=(const GroupPlayer&);
};

对于派生的副本,我写了这个:

GroupPlayer::GroupPlayer(const GroupPlayer& player):ptr(new IdPlayer(*(player.ptr))){}

但我不确定它是否正确......我是否也应该添加LevelPlayer(player)

【问题讨论】:

    标签: c++ class inheritance copy derived-class


    【解决方案1】:

    看看构造函数,看看

    ptr(new IdPlayer(*ptr))
    ptr(new IdPlayer(*(player.ptr)))
    

    我得出结论,你不需要默认的指针和复制构造函数。制作成员和第二个构造函数

    IdPlayer player;
    GroupPlayer(int level, int id, const IdPlayer& player): LevelPlayer(level, id), player{player} {}
    

    而不是IdPlayer* ptr; 并删除其他构造函数。最后,在代码中标点符号后使用空格,这样可以方便阅读和代码选择。

    【讨论】:

      【解决方案2】:

      我不确定它是否正确...我还应该添加LevelPlayer(player)吗?

      是的,派生类拷贝构造函数需要显式调用基类拷贝构造函数:

      GroupPlayer::GroupPlayer(const GroupPlayer& player)
          : LevelPlayer(player), ptr(new IdPlayer(*(player.ptr)))
      {
      }
      

      由于您已经实现了派生类复制构造函数,并且基类构造函数接受了一个输入参数,因此您需要为该参数传入一个值。如果不这样做,则会调用基类默认构造函数,因此不会从player 复制levelid

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-30
        相关资源
        最近更新 更多