具有相同构造函数的许多类

Many classes with the same constructors

本文关键字:许多类 构造函数      更新时间:2023-10-16

我有许多类,它们只是在参数上相似。有没有办法写得更简洁/整齐?编写包含成员变量的基类会有所帮助,但我仍然需要为每个类写出构造函数。

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 的编译器,这就是继承构造函数的用途......检查并使用它

这是如何应用它...

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