C++0x initializer list example

馋奶兔 提交于 2019-12-04 03:10:37
Klaim

You last examples wouldn't be allowed as you ask for pointers but try to provide local temporary objects instead.

std::vector<Ask*> ui ={
    new AskString{"Enter your name: ", 3, 25},
    new AskString{"Enter your city: ", 2, 25},
    new Ask{"Enter your age: "}
    };

That would be allowed and there would be no type ambiguity.

That would be right too :

std::vector<Ask*> ui ={
        new AskString("Enter your name: ", 3, 25),
        new AskString("Enter your city: ", 2, 25),
        new Ask("Enter your age: ")
        };

And your example is more like :

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

and again there would be no ambiguity on the types.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!