我有许多类只在它们所采用的参数中相似。有没有办法更简洁/整洁地写这个?编写包含成员变量的基类会有所帮助,但我仍然需要为每个类写出构造函数。
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)
{};
};
答案 0 :(得分:2)
假设您使用的是支持C ++ 11的编译器,那就是inheriting constructor的用途...... 检查并使用它
以下是如何应用它......
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);
}