如何初始化参数化构造函数的对象数组

时间:2012-02-14 18:18:50

标签: c++ c++11

我需要初始化参数化构造函数的对象数组。我怎么能以最好的方式做到这一点?

   # include<iostream>
   # include<conio.h>
   # include<stdio.h>

   using namespace std;

   class A
   {
    public:
    int a;       
    A();
    A(int x)
    {
     a=x;
    }      
   };
   int main()
   {
    A *a1,a2(1);
    a1 = (A*)malloc(sizeof(A)*10); // equivalent to A[10]. 
    for(int i=0;i<10;i++) a1[i]=a2; // Initialization is important in any program.
    for(int i=0;i<10;i++) cout<<a1[i].a; 
    getch(); 
    return 0;   
   }

这确实有效,但还有其他方法比这更好吗?

3 个答案:

答案 0 :(得分:4)

C ++方式是使用std :: vector。

std::vector<A>   a1(10, 1);

创建由A初始化的10 1

答案 1 :(得分:0)

使用std :: vector构造函数来获取大小和基本元素:

A a2(1);
std::vector<A> tab(10, a2);

答案 2 :(得分:-1)

请注意malloc不构造对象,因此调用a1[i]=a2是不好的形式。它似乎似乎工作正常,因为它们是POD-ish对象,但这不是做C ++的正确方法。这是未定义的行为,这是完全不可预测的。它可能会连续工作一万次,然后删除您的银行帐户。您应该使用new代替 构造。或者更好的是,使用矢量,就像其他答案所暗示的那样。此外,请确保默认构造函数初始化数据,初始化将不用担心。

如果真的必须使用malloc,初始化的“正确方法”是:

std::uninitialized_copy(a1, a1+10, a2); //constructs and assigns

大致相当于:

{
    int i=0;
    try {
        for(i=0; i<10; ++i)
           new(a1+i)A(a2); //constructs and initializes in the buffer
    } catch(...) { 
        try {
            for(; i>=0; --i)
               (a1+i)->~A(); //destroy if an error occured
        } catch(...) { 
            std::terminate();
        }
        throw;
    }
}
相关问题