C++ 具有相同构造函数的许多类
我有很多类,它们的参数非常相似。有没有办法写得更简洁/整洁?编写一个包含成员变量的基类会有所帮助,但我仍然需要为每个类编写构造函数C++ 具有相同构造函数的许多类,c++,class,inheritance,C++,Class,Inheritance,我有很多类,它们的参数非常相似。有没有办法写得更简洁/整洁?编写一个包含成员变量的基类会有所帮助,但我仍然需要为每个类编写构造函数 class CommandDrawLiver { protected: int age; Species species; double r, g, b; public: CommandDrawLiver( int _age, Species _species, double _r, d
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);
}
某种工厂功能模板<代码>模板T makeCommandDraw(int,Species&,double,double,double){/…}。欢迎使用。我刚刚编辑了答案以显示用法,如果这解决了您的问题,您可以将其标记为已回答:-)