【发布时间】:2019-04-27 20:41:32
【问题描述】:
我有一个模拟窗口的程序;所以我将窗口的内容存储在成员数据content 中,这是一个std::string 类型:
class Window {
using type_ui = unsigned int;
public:
Window() = default;
Window(type_ui, type_ui, char);
void print()const;
private:
type_ui width_{};
type_ui height_{};
char fill_{};
std::string content_{};
mutable type_ui time_{};
};
Window::Window(type_ui width, type_ui height, char fill) :
width_{ width }, height_{ height }, fill_{ fill },
content_{ width * height, fill } { // compile-time error here?
//content( width * height, fill ) // works ok
}
void Window::print()const {
while (1) {
time_++;
for (type_ui i{}; i != width_; ++i) {
for (type_ui j{}; j != height_; ++j)
std::cout << fill_;
std::cout << std::endl;
}
_sleep(1000);
std::system("cls");
if (time_ > 10)
return;
}
}
int main(int argc, char* argv[]) {
Window main{ 15, 25, '*' };
main.print();
std::string str{5u, '*'}; // compiles but not OK
std::string str2(5u, '*'); // compiles and OK
cout << str << endl; // ♣* (not intended)
cout << str2 << endl; // ***** (ok)
std::cout << std::endl;
}
正如您在上面看到的,我无法使用编译器抱怨“缩小类型”的curly-braces-initializer-list 初始化成员content。但它适用于“直接初始化”。
为什么我不能在 Constructor-initializer-list 中使用上面的 Curly-brace-initialization-list 来调用
std::string(size_t count, char)。为什么这个
std::string str{5u, '*'}; // compiles but not OK有效但没有提供预期的输出?对我来说非常重要的是为什么相同的初始化在构造函数成员初始化列表中不起作用但在
main中起作用(没有预期的结果)?
【问题讨论】:
标签: c++ c++11 initializer-list stdstring