我想看看这个现有代码示例如何能够利用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之间的区别如何处理?
答案 0 :(得分:9)
您最后的示例将不会被允许,因为您要求指针,但尝试提供本地临时对象。
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}
};
再次对类型没有任何歧义。
答案 1 :(得分:-2)
c ++初始化列表是同源,这意味着它必须具有相同的类型,因此示例#2已经出局。如果您在示例1中使用new
,则可以使用它。