有条件地调用不同的构造函数

时间:2017-02-28 16:57:17

标签: c++ constructor

我想根据运行时条件调用同一类的不同构造函数。构造函数使用不同的初始化列表(:之后的一堆内容),因此我无法在构造函数中处理条件。

例如:

#include <vector>
int main() {
    bool condition = true;
    if (condition) {
        // The object in the actual code is not a std::vector.
        std::vector<int> s(100, 1);
    } else {
        std::vector<int> s(10);
    }
    // Error: s was not declared in this scope
    s[0] = 1;
}

我想我可以使用指针。

#include <vector>
int main() {
    bool condition = true;
    std::vector<int>* ptr_s;
    if (condition) {
        // The object in the actual code is not a std::vector.
        ptr_s = new std::vector<int>(100, 1);
    } else {
        ptr_s = new std::vector<int>(10);
    }
    (*ptr_s)[0] = 1;
    delete ptr_s;
}

如果我没有为我的班级编写移动构造函数,是否有更好的方法?

2 个答案:

答案 0 :(得分:2)

另一种解决方案是创建一个类,默认的构造函数不会进行分配,计算(以及所有硬件工作),而是有一个函数,例如initialize,并为每个构造函数类型重载它做真正的工作。

例如:

int main() {
    bool condition = true;
    SomeClass object;
    if (condition) {
        object.initialize(some params 1)
    } else {
        object.initialize(some params 2)
    }
}

或者你可能希望默认构造函数做一些有意义的事情,在这种情况下,使一个构造函数接受某个“虚拟”类型的对象,例如DoNothing而是:

 SomeClass object(DoNothing())

答案 1 :(得分:1)

你不能按照

的方式做点什么
std::vector<int> ptr_s;
if (condition) {
    ptr_s.resize(100);
} else {
    ptr_s.resize(10);
}

相关问题