我有许多类,它们的参数仅相似。有没有一种方法可以更简洁/简洁地编写此代码?编写一个包含成员变量的基类会有所帮助,但是我仍然需要为每个类写出构造函数。

class CommandDrawLiver {
    protected:
        int age;
        Species species;
        double r, g, b;
    public:
        CommandDrawLiver( int _age, Species _species, double _r, double _g, double _b )
          : age(_age), species(_species), r(_r), g(_g), b(_b)
          {};
};
class CommandDrawBrain {
    protected:
        int age;
        Species species;
        double r, g, b;
    public:
        CommandDrawBrain( int _age, Species _species, double _r, double _g, double _b )
          : age(_age), species(_species), r(_r), g(_g), b(_b)
          {};
};
class CommandDrawHeart {
    protected:
        int age;
        Species species;
        double r, g, b;
    public:
        CommandDrawHeart( int _age, Species _species, double _r, double _g, double _b )
          : age(_age), species(_species), r(_r), g(_g), b(_b)
          {};
};

最佳答案

假设您使用的是支持C++ 11的编译器,那么inheriting constructor就是...
checkout 并使用

这是应用方法...

class Species{};

class CommandDraw {
    protected:
        int age;
        Species species;
        double r, g, b;

    public:
        CommandDraw( int _age, Species _species, double _r, double _g, double _b )
          : age(_age), species(_species), r(_r), g(_g), b(_b)
          {};
};

class CommandDrawLiver : public CommandDraw {
    public:
        using CommandDraw::CommandDraw;
};
class CommandDrawBrain : public CommandDraw {
    public:
        using CommandDraw::CommandDraw;
};
class CommandDrawHeart : public CommandDraw {
    public:
        using CommandDraw::CommandDraw;
};

int main() {
    CommandDrawLiver cd(34, Species(), 12, 45, 67);
    }

关于c++ - 许多具有相同构造函数的类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35288419/

10-10 17:26