C++ 如何初始化构造函数需要两个或多个参数的对象数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9656576/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 13:07:57  来源:igfitidea点击:

How can I initialize an array of objects whose constructor require two or more arguments?

c++

提问by Yishu Fang

suggest we have an array of class A's objects, and class A's constructor require two arguments, like this:

建议我们有一个 A 类对象的数组,A 类的构造函数需要两个参数,如下所示:

class A  
{  
public:  
    A( int i, int j ) {}  
};  

int main()  
{
    const A a[3] = { /*How to initialize*/ };

    return 0;
}

How to initialize that array?

如何初始化该数组?

回答by Kerrek SB

Say:

说:

const A a[3] = { {0,0}, {1,1}, {2,2} };

On older compilers, and assuming Ahas an accessible copy constructor, you have to say:

在较旧的编译器上,并假设A有一个可访问的复制构造函数,您必须说:

const A a[3] = { A(0,0), A(1,1), A(2,2) };

C++ used to be pretty deficient with respect to arrays (certain initializations just were not possible at all), and this got a little better in C++11.

C++ 过去在数组方面非常有缺陷(某些初始化根本不可能),而这在 C++11 中变得更好一些。

回答by Dietmar Kühl

As long as the type has a copy constructior (whether synthesized or explicitly defined) the following works:

只要类型具有复制构造函数(无论是合成的还是显式定义的),以下工作:

A array[] = { A(1, 3), A(3, 4), A(5, 6) };

This work both with C++2003 and C++ 2011. The solution posted by KerrekSB certainly does not work with C++ 2003 but may work withC++ 2011 (I'm not sure if it works there).

这适用于 C++2003 和 C++ 2011。KerrekSB 发布的解决方案当然不适用于 C++ 2003,但可能适用于 C++ 2011(我不确定它是否适用于那里)。

回答by James Shao

you can provide a default constructor and initialize your array as normal. After successful initialization, use a loop to reassign values to each member

您可以提供一个默认构造函数并像往常一样初始化您的数组。初始化成功后,使用循环为每个成员重新赋值

回答by hamed

i think it should be like this

我觉得应该是这样

const A a[3] = { A(1, 2), A(3, 4), A(5, 6) };

const A a[3] = { A(1, 2), A(3, 4), A(5, 6) };