具有相同构造函数的许多类
Many classes with the same constructors
我有许多类,它们只是在参数上相似。有没有办法写得更简洁/整齐?编写包含成员变量的基类会有所帮助,但我仍然需要为每个类写出构造函数。
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);
}
相关文章:
- 在类构造函数中传递对外部函数的引用
- 具有enable_if外部类原型的模板类构造函数定义
- 自动重复 extern "C"函数中的类构造函数采用的相同参数
- 模板化类构造函数的模板实例化
- C++派生的类构造函数
- 在类构造函数中使用结构变量
- 在类构造函数中定义结构变量的参数
- 为什么类构造函数为其成员生成析构函数?
- C++ - 空模板类构造函数不初始化值
- 如何使用 swig 修改类构造函数以保留对其中一个构造函数参数的引用?
- 在具有向量的类构造函数中进行析构函数调用
- 处理简单 cpp 类构造函数中的错误
- C++17 使用驱动类常量作为基类构造函数的参数来初始化基类构造函数
- 如何在 c++ 中将整个数组初始化为类构造函数中的单个元素
- 如何检测除整数以外的任何内容是否传递给我的类构造函数?
- 派生类(构造函数具有参数)和基类(构造函数缺少参数)之间没有可行的转换
- QT 如何将 Qlist 传递给类构造函数
- 使用指向成员函数的指针在另一个类中调用类构造函数
- C++ 关于两个类构造函数的问题
- 在成员构造函数之后调用基类构造函数