我需要初始化参数化构造函数的对象数组。我怎样才能以最好的方式做到这一点?
# 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;
}
这确实有效,但还有比这更好的其他方法吗?
最佳答案
C++ 方法是使用 std::vector。
std::vector<A> a1(10, 1);
创建 10 个由 1
初始化的 A
。
关于c++ - 如何初始化参数化构造函数的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9282097/