简体   繁体   English

在C ++中,当我想在初始化类对象数组时通过构造函数初始化类成员时,我该怎么办?

[英]In C++, What should I do when I want to initialize class members via constructor when I initialize a class object array?

I thought I could do the following: 我以为我可以做到以下几点:

#include <iostream>

using namespace std;

class cl
{
  public:
    double* Arr;
    cl(int);
};

cl::cl(int i)
{
    Arr=new double[i];
    Arr[0]=11;
};

int main()
{
    cl* BB;
    BB=new cl(3)[3];      /* I want to initialize a class member Arr for each element of the class cl array BB when I initialize this array by means of constructor. What should I do? */
    cout << cl[1].Arr[0] << endl;                                                                                                   

    return 0;
}

but obviously something is wrong with the line where I noted. 但是很明显,我注意到的那一行是有问题的。 The compiler wouldn't compile. 编译器无法编译。

In C++11 you can use brace initializer: 在C ++ 11中,您可以使用大括号初始化器:

cl* BB = new cl[3] {1, 2, 3};

or more verbose, so it's clear that the numbers are passed as arguments to constructors of different objects: 或者更详细,所以很明显这些数字作为参数传递给不同对象的构造函数:

cl* BB = new cl[3] {{1}, {2}, {3}}; 

Though as you are allocating memory dynamically anyway, it's better to use std::vector , also it's more convenient if you want to initialize large number of objects with the same parameters: 虽然你无论如何动态分配内存,但最好使用std::vector ,如果你想用相同的参数初始化大量的对象,它也会更方便:

std::vector<cl> BB(300, 3);

However, std::vector initialization won't compile if cl doesn't have a copy constructor. 但是,如果cl没有副本构造函数,则不会编译std::vector初始化。 In that case you can use emplace_back() : 在这种情况下,您可以使用emplace_back()

vector<cl> BB;
BB.reserve(300);
for(int i = 0; i < 300; ++i)
    BB.emplace_back(3);

This in turn can be wrapped into a template back_emplacer_iterator to use with std::fill_n 这反过来可以包装到模板back_emplacer_iterator以与std::fill_n一起使用

There are several approaches: 有几种方法:

  • C++11 initializer list C ++ 11 初始化列表

     cl* BB = new cl[3] {42, 42, 42}; 
  • STL-vector (recommended) STL-vector(推荐)

     std::vector<cl> BB( 3, cl( 42 ) ); 

As pre-C++11 there are also other more involved solutions relying on placement new operator although I'd not recommend this. 作为C ++ 11之前的版本,还有其他涉及更多的解决方案,它们依赖于放置新运算符,尽管我不建议这样做。

The format of a new-expression is a type, followed by an initializer. new表达式的格式是一种类型,后跟一个初始化程序。 If you want to allocate an array of 3 cl objects then the type is cl[3] . 如果要分配3个cl对象的数组,则类型为cl[3] You can't say cl(3)[n] because cl(3) is not a type. 你不能说cl(3)[n]因为cl(3)不是一个类型。

In C++03 the only valid initializer for a dynamically-allocated array is () which value-initializes each element, but you can't do that as your type doesn't have a default constructor. 在C ++ 03中,动态分配数组的唯一有效初始值设定项是() ,它对每个元素进行值初始化,但由于您的类型没有默认构造函数,所以不能这样做。

In C++11 you can use an initializer-list to pass arguments to each array element: 在C ++ 11中,您可以使用初始化列表将参数传递给每个数组元素:

cl* ptr = new cl[3]{ 3, 3, 3};

Each element in the array will be initialized by the default constructor (no argument constructor). 数组中的每个元素都将由默认构造函数(无参数构造函数)初始化。 After that you may call any function that does the desired task. 之后,您可以调用执行所需任务的任何函数。 Corrected program example: 更正的程序示例:

class cl
{
  public:
    double* Arr;
    cl(int i = 0);
    ~cl();
    void allocArr(int i=0);
};

cl::cl(int i)
{
    allocArr(i);
}

void cl::allocArr(int i)
{
    if (i <= 0) {
        Arr = (double *) NULL;
    }
    else {
        Arr=new double[i];
        Arr[0]=11;
    }
};

cl::~cl() {
    if (Arr)
      delete [] Arr;
}

int main()
{
    cl* BB;
    BB=new cl[3]; // default constructor 
    for (int i = 0; i < 3; i++) {
        BB[i].allocArr(3);
    }

    cout << BB[1].Arr[0] << endl;                                                                                                   

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 C++ class 中初始化可变大小数组? - How do I initialize a variable size array in a C++ class? 如何根据 C++ 中的参数初始化 class 的成员? - How can I initialize members of a class based on a parameter in C++? C ++ - 如何从类的构造函数初始化单独类的构造函数? - C++ - How do I initialize a constructor of a separate class from the constructor of a class? 如何通过C ++中构造函数的初始化列表来值初始化类的私有结构成员? - how can I value initialize private struct member of class via initialization list of constructor in c++? c++ 如何在构造函数中初始化成员数组? - c++ How do I initialize a member array in a constructor? 如何在类构造函数中初始化动态分配的数组 - How do I initialize a dynamically allocated array within a class constructor 我是否应该始终在C ++中初始化类的每个数据成员? - Should I always initialize every data member of a class in c++? 为什么要在C ++中初始化静态类变量? - Why should I initialize static class variables in C++? C ++:我应该将构造函数体中指定的指针成员初始化为NULL吗? - C++: Should I initialize pointer members that are assigned to in the constructor body to NULL? 我应该使用虚拟&#39;Initialize()&#39;函数来初始化我的类的对象吗? - Should I use virtual 'Initialize()' functions to initialize an object of my class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM