C++ Instantiate, inside another class, a class-type variable from a group of classes with same constructor

只谈情不闲聊 提交于 2019-12-25 08:09:27

问题


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

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

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?

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.


回答1:


You could have an interface class with those common member variables

class I
{
public:
    virtual ~I() = default;
protected:
    double 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) { ... };
};

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



回答2:


You can derive those classes from one common class. For example:

class Test {
    double Val1, Val2;
public:
    Test() {}
};

class A: public Test { 
    /* constructor and class-specific variables only,
       don't declare Val1 & Val2 here */
}

Then, make m_class a pointer to Test and instantiate the classes in your switch with new.



来源:https://stackoverflow.com/questions/38976921/c-instantiate-inside-another-class-a-class-type-variable-from-a-group-of-cla

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!