如何在保持高效的同时正确使用继承?

Vin*_*tch 1 c++ inheritance class

我这里有一些课程:

class weapons
{
protected:
    int damage, armor, cost;
};

class sword : public weapons
{
public:
    // Initialization for the sword class.
    void initialize()
    {

    }
};

class shield : public weapons
{

};
Run Code Online (Sandbox Code Playgroud)

我开始研究这些,我不记得如何设置每个继承类的伤害,护甲和成本.我该怎么做呢?什么是快速方式(不一定非常容易)?

das*_*ght 6

在类中设置变量的正确方法是通过其类的构造函数.派生类应使用初始化列表在其基类中设置变量.

class weapon {
protected:
    int damage, armor, cost;
    weapon(int d, int a, int c) : damage(d), armor(a), cost(c) {}
};

class sword : public weapon {
private:
    int weight;
public:
    sword(int d, int a, int c, int w) : weapon(d, a, c), weight(w) {}
};
Run Code Online (Sandbox Code Playgroud)

另外,如果子控制在基础值(即用户没有通过damage,armor或者cost你可以这样做:

sword(int w) : weapon(30, 5, 120), weight(w) {}
Run Code Online (Sandbox Code Playgroud)

编译器将优化此代码以正确内联,因此您不必担心添加额外的构造函数层会导致性能下降.