0

假设我有一个Entity带有变量的类,它在该类x中定义。0

好吧,然后我创建了一个派生类Player,但我希望默认情况下Player继承的是而不是,所以我创建的每个默认情况下都是。x10Playerx1

这可能吗?

如果是,我该怎么做?

4

2 回答 2

2

是的,这是可能的,我已经阅读了评论,并且我认为您希望基成员是私有的,一种选择是继承基类构造函数。

样本 1

class Entity{
private:
    int x;
public:
    Entity(int i = 0) : x(i) {} //initialize x to 0
    int getX() {return x;}
};

class Player: public Entity{
public:
    Player() : Entity(1) {}   //inherit base class constructor initializing x to 1
};

这个实现有一个潜在的弱点,它允许构造初始化对象x。如果您不希望这样,您可以拥有一个受保护的构造函数,它允许派生类指定成员值,从而防止构造可以初始化的对象x

样本 2

class Entity {    
    int x = 0;    
public:
    Entity() = default; //default construtor
    int getX(){return x;}

protected:
    Entity(int i) : x(i) {} //protected constructor, 
};

class Player : public Entity {
public:
    Player() : Entity(1) {}
};

用法

#include <iostream>

using std::cout;
using std::endl;

int main()
{   
    Entity e;
    cout << e.getX() << endl;

    Player p;
    cout << p.getX();

    return 0;
}

根据您的类的复杂性,您还可以使受保护的构造函数显式

输出

0
1

请注意,这是一个非常简化的版本,您应该遵守类构造规则,例如三/五/零规则

于 2020-04-20T20:44:24.820 回答
1
class Entity {
  private:
    int x;
  public:
    Entity() : x(0)
  {}
    void set_x(int y){
      x = y;
    }
    int get_x(){
      return x;
    }

};

class Player : public Entity {
  public:
    Player() 
    {
      set_x(1);
    }
};
于 2020-04-20T19:41:54.780 回答