使用花括号初始化临时聚合对象
假设我有一个类:
class Aggregate {
public:
int x;
int y;
};
我知道如何使用大括号初始化对象:
Aggregate a1 = { 1500, 2900 };
但是我找不到正确的语法来创建临时对象并将其作为参数传递给某些方法,例如:
void frobnicate(const Aggregate& arg) {
// do something
}
//...
frobnicate(Aggregate {1500, 2900}); // what should this line look like?
最简单的方法是将构造函数添加到 Aggregate 类,但假设我无权访问 Aggregate 标头。另一个想法是编写某种工厂方法,即
Aggregate makeAggregate(int x, int y).
我也可以创建一个对象,然后将其作为参数传递,等等。
有很多解决方案,但我只是好奇是否可以使用来实现这个目标大括号初始化。
Let's say I have a class:
class Aggregate {
public:
int x;
int y;
};
I know how to initialize an object using curly braces:
Aggregate a1 = { 1500, 2900 };
But I can't find a proper syntax to create temporary object and pass it as an argument to some method, for example:
void frobnicate(const Aggregate& arg) {
// do something
}
//...
frobnicate(Aggregate {1500, 2900}); // what should this line look like?
The easiest way would be to add the constructor to Aggregate class, but let's assume I don't have an access to the Aggregate header. Another idea would be to write some kind of factory method, i.e.
Aggregate makeAggregate(int x, int y).
I can also create an object and then pass it as an argument, etc. etc.
There are many solutions, but I'm just curious if it's possible to achieve this goal using curly braces initialization.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您想要的可以通过 C++0x 初始化列表实现。
GCC 4.4 已经通过
-std=c++0x
标志支持这一点。可能VS2010 CTP也支持这个(如果我错了请纠正我)。使用 C++98/C++03,您必须编写并调用构造函数。
What you want is possible with C++0x initializer lists.
GCC 4.4 already supports this with
-std=c++0x
flag. Possibly VS2010 CTP supports this too (correct me if I'm wrong).With C++98/C++03 you will have to write and invoke a constructor.
现在不可能了。因此,新标准 C++ 0x 引入了 初始化器列表 和Uniform_initialization。
It is not possible now. Because of this the new standard C++ 0x introduced the concept of a Initializer lists and Uniform_initialization.
“有很多解决方案,但我只是好奇是否可以使用大括号初始化来实现此目标。”
不可能。如果您无法更改源代码,那么您唯一的选择是将其包装在内联函数或辅助结构中:
编辑:删除不相关的构造函数解决方案。
"There are many solutions, but I'm just curious if it's possible to achieve this goal using curly braces initialization."
Not possible. If you can't change the source then your only options are to wrap that in an inline function or a helper struct:
edit: removed irrelevant constructor solution.