C++0x 初始值设定项列表示例
我想看看这个现有代码示例如何利用 C++0x 初始化列表功能。
示例 0:
#include <vector>
#include <string>
struct Ask {
std::string prompt;
Ask(std::string a_prompt):prompt(a_prompt){}
};
struct AskString : public Ask{
int min;
int max;
AskString(std::string a_prompt, int a_min, int a_max):
Ask(a_prompt), min(a_min), max(a_max){}
};
int main()
{
std::vector<Ask*> ui;
ui.push_back(new AskString("Enter your name: ", 3, 25));
ui.push_back(new AskString("Enter your city: ", 2, 25));
ui.push_back(new Ask("Enter your age: "));
}
它是否支持这样的内容:
示例 1:
std::vector<Ask*> ui ={
AskString("Enter your name: ", 3, 25),
AskString("Enter your city: ", 2, 25),
Ask("Enter your age: ")
};
或者它必须具有这样的文字吗?:
示例 2:
std::vector<Ask*> ui ={
{"Enter your name: ", 3, 25},
{"Enter your city: ", 2, 25},
{"Enter your age: "}
};
如果是这样,将如何处理 AskString 和 Ask 之间的差异?
I would like to see how this example of existing code would be able to take advantage of the C++0x initializer list feature.
Example0:
#include <vector>
#include <string>
struct Ask {
std::string prompt;
Ask(std::string a_prompt):prompt(a_prompt){}
};
struct AskString : public Ask{
int min;
int max;
AskString(std::string a_prompt, int a_min, int a_max):
Ask(a_prompt), min(a_min), max(a_max){}
};
int main()
{
std::vector<Ask*> ui;
ui.push_back(new AskString("Enter your name: ", 3, 25));
ui.push_back(new AskString("Enter your city: ", 2, 25));
ui.push_back(new Ask("Enter your age: "));
}
Would it support something like this:
Example1:
std::vector<Ask*> ui ={
AskString("Enter your name: ", 3, 25),
AskString("Enter your city: ", 2, 25),
Ask("Enter your age: ")
};
Or must it have literals like this?:
Example2:
std::vector<Ask*> ui ={
{"Enter your name: ", 3, 25},
{"Enter your city: ", 2, 25},
{"Enter your age: "}
};
If so how would the difference between AskString and Ask be handled?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您请求指针时,您最后的示例将不被允许,而是尝试提供本地临时对象。
这是允许的,并且不会有类型歧义。
这也是对的:
你的例子更像是:
类型上不会有任何歧义。
You last examples wouldn't be allowed as you ask for pointers but try to provide local temporary objects instead.
That would be allowed and there would be no type ambiguity.
That would be right too :
And your example is more like :
and again there would be no ambiguity on the types.
C++ 初始值设定项列表是同质的,这意味着它必须具有相同的类型,因此示例#2 已不再适用。 如果您在示例 1 中使用了
new
,那么它就可以工作。A c++ initializer list is homogenous, meaning it must have all the same type, so example #2 is out. If you used
new
in example 1, it would work.