【发布时间】:2015-11-05 20:39:27
【问题描述】:
// pointer to classes example
// runs with no problem
#include <iostream>
using namespace std;
class Rectangle {
int width, height;
public:
Rectangle(int x, int y) : width(x), height(y) {}
int area(void) { return width * height; }
};
int main() {
Rectangle obj (3, 4);
Rectangle * foo, * bar, * baz;
foo = &obj;
bar = new Rectangle (5, 6);
baz = new Rectangle[2] { {2,5}, {3,6} };
cout << "obj's area: " << obj.area() << '\n';
cout << "*foo's area: " << foo->area() << '\n';
cout << "*bar's area: " << bar->area() << '\n';
cout << "baz[0]'s area:" << baz[0].area() << '\n';
cout << "baz[1]'s area:" << baz[1].area() << '\n';
delete bar;
delete[] baz;
return 0;
}
我对这里的这行代码有点(不是双关语)困惑:
baz = new Rectangle[2] {{2,5}, {3,6}};
我见过这样的代码:
int *foo = new int[3] {1,2,3};
我完全理解。但是这里{{2,5}, {3,6}} 的语法是什么?如何像这样初始化类对象数组?我搜索了许多在线 c++ 参考资料,但没有任何线索。
【问题讨论】:
-
{2,5}初始化第一个数组成员,{3,6}初始化第二个数组成员。它与int[3]的情况没有什么不同,只是每个初始化器都是另一个用大括号括起来的列表。
标签: c++ arrays class c++11 initialization