C ++实例化,在另一个类中,一个类型变量从一组具有相同构造函数的类 [英] C++ Instantiate, inside another class, a class-type variable from a group of classes with same constructor
问题描述
我在C ++中不高级。假设我有一组类,从 A
到任何(数字将随时间增长),使用相同类型的构造函数。假设它看起来像这样:
I am not advanced in C++. Suppose I have a group of classes, from A
to whatever (the number will grow in time), that use the same type of constructor. Suppose it looks like this:
class A
{
private:
double m_x, m_y;
public:
A(const double &x, double &y, const short &n) { ... };
};
每个类都有相同的 m_x,m_y
变量,但它们的计算方式不同。现在有另一个类, Bla
,需要使用前一组类的构造函数,类似这样:
Each of these classes have the same m_x, m_y
variables, but they calculate it differently. Now there's another class, say Bla
, who needs to use the constructors from the previous group of classes, something like this:
class Bla
{
private:
Class m_class;
public:
Bla(const double &x, const double &y, const double &z, const short &i)
{
switch (i)
{
case 1: m_class = A::A(...); break;
case 2: m_class = B::B(...); break;
...
}
}
};
在构造函数中的 switch(i)
根据 i
选择组的构造函数之一。如何使类中的m_class
变量 Bla
与开关)
在构造函数中?我应该选择什么类型的变量,或如何?
The switch (i)
in the constructor chooses one of the group's constructor according to i
. How can I make the Class m_class
variable inside Bla
to be consistent with the switch (i)
in the constructor? What type of variable should I choose, or how?
或者, m_class
只需要保存 m_x,m_y
来自组中的一个类的变量,要进一步处理/计算/ etc,还有另一种方法吗?
Alternatively, m_class
only needs to hold the m_x, m_y
variables coming from one of the classes in the group, to be further processed/calculated/etc, is there another method of doing this? I hope I managed to be clear about this.
推荐答案
你可以有一个包含这些常用成员变量的接口类
You could have an interface class with those common member variables
class I
{
public:
virtual ~I() = default;
protected:
double m_x, m_y;
};
然后从中导出你的具体类,每个将填充 m_x
和 m_y
。
Then derive your concrete classes from that, each of which will populate m_x
and m_y
differently.
class A : public I
{
public:
A(const double &x, double &y, const short &n) { ... };
};
然后你的 Bla
工厂并根据您的 i
参数取得特定类型的 I
Then your Bla
constructor essentially acts as a factory and makes specific types of I
depending on your i
parameter
class Bla
{
private:
std::unique_ptr<I> m_class;
public:
Bla(const double &x, const double &y, const double &z, const short &i)
{
switch (i)
{
case 1: m_class = std::unique_ptr<I>(new A(...)); break;
case 2: m_class = std::unique_ptr<I>(new B(...)); break;
...
}
}
};
这篇关于C ++实例化,在另一个类中,一个类型变量从一组具有相同构造函数的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!