C ++ 0x初始化程序列表示例
我想看看现有代码的这个例子如何能够利用C ++ 0x初始值设定项列表功能。
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: "));
}
它会支持这样的事情吗?
例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之间的区别将如何处理?
你最后的例子不会被允许,因为你要求指针,但是尝试提供本地临时对象。
std::vector<Ask*> ui ={
new AskString{"Enter your name: ", 3, 25},
new AskString{"Enter your city: ", 2, 25},
new Ask{"Enter your age: "}
};
这将被允许,并且不存在类型歧义。
这也是对的:
std::vector<Ask*> ui ={
new AskString("Enter your name: ", 3, 25),
new AskString("Enter your city: ", 2, 25),
new Ask("Enter your age: ")
};
你的例子更像是:
std::vector<Ask> ui ={ // not pointers
{"Enter your name: "},
{"Enter your city: "},
{"Enter your age: "}
};
std::vector<AskString> uiString ={ // not pointers
{"Enter your name: ", 3, 25},
{"Enter your city: ", 2, 25},
{"Enter your age: ", 7, 42}
};
而且在类型上也不会含糊不清。
c ++初始化程序列表是同质的,这意味着它必须具有所有相同的类型,所以示例#2已经结束。 如果您在示例1中使用了new
,它将起作用。
上一篇: C++0x initializer list example
下一篇: How to use count and group by at the same select statement