如何使用重载构造函数创建两个动态对象

how can I create two dynamic objects with overloaded constructor?

本文关键字:两个 动态 对象 何使用 重载 构造函数 创建      更新时间:2023-10-16

请看看下面的代码,这是一个简单的主题,但我不知道。

class trial{
public:
    trial(){
        y = -1;
    }
    trial(int x){
        y = x;
    }
public:
        int y;
};

int main() {
    trial *trialPtr = new trial();     // creates a dynamic object with empty constructor
    trial *trialPtr1 = new trial(1);   // creates a dynamic object with overloaded constructor
    trial *trialPtr2 = new trial[2];   // creates two dynamic objects with empty constructor
    return 0;
}

我的问题是,如何用重载构造函数创建两个动态对象?

对于内置数组

是不可能的但是考虑使用std::vector
vector<trial> var(10, trail(4));

这有一个额外的好处,你不需要担心内存管理

添加一个丑陋的解决方案,因为OP显然想要它。在创建数组之前,将FOO设置为合适的值。请在拒绝投票前阅读评论

int FOO = -1;
class trial{
public:
    trial(){
        y = FOO;
    }
    trial(int x){
        y = x;
    }
public:
        int y;
};
int main(int argc, _TCHAR* argv[])
{
    FOO = 4;
    trial *trialPtr2 = new trial[2];
    return 0;
}

数组在c++ 98/03中是有问题的,因为通常不能完全自由地初始化它们。c++ 11通过统一初始化解决了这个问题。现在你可以说

new trial[2] { 1, 1 };

在c++中没有语法方法可以做到这一点,就像下面这个(不正确的)示例:*trialPtr2 = new trial2;如果您希望使用数组,则必须执行for循环:

trial *trialPtr2[] = new (*trial)[2];
for (int i = 0; i < 2; i++)
{
    trialPtr2[i] = new trial(3);
}