8

我想看看这个现有代码示例如何能够利用 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 之间的差异?

4

2 回答 2

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}
    };

并且在类型上也不会有歧义。

于 2009-05-25T17:33:16.230 回答
-2

C++ 初始化器列表是同质的,这意味着它必须具有所有相同的类型,因此示例 #2 不可用。如果您new在示例 1 中使用,它会起作用。

于 2009-05-25T17:33:00.893 回答