简体   繁体   中英

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

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.

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM