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

标签 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;   
   }

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

最佳答案

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

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

创建 10 个由 1 初始化的 A

关于c++ - 如何初始化参数化构造函数的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9282097/

相关文章:

c++ - 为什么 C++17 中 std::function 的 operator() 会发生变化?

c++ - 在 C++11 中初始化 C 字符串?

c++ - 读取 cmd 生成的文件,结果出现 3 个奇怪的符号

c++ - vc++ 2010/2012:包含 unique_ptr 的结构的 std::vector 编译器错误

c++ - Qt 中的日期时间

javascript - 添加事件监听器和中断

c++ - 如何从自身加入 std::thread(在 C++11 中)

c++ - C++中 "main"线程的id

c++ - 构建本身就是 shared_ptr 类型的模板化容器

c++ - Linux 上的 .NET Core - 编码(marshal)结构