У меня есть программа, которая имитирует окно; Таким образом, у меня есть содержимое окна, хранящееся в элементе данных 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;
}
Как вы можете видеть выше, я не смог инициализировать элемент content
с curly-braces-initializer-list
, на что компилятор жалуется на "тип сужения". Но это работает с «прямой инициализацией».
Почему я не могу использовать список Curly-brace-initialization-list выше в Constructor-initializer-list для вызова std::string(size_t count, char)
.
Почему это std::string str{5u, '*'}; // compiles but not OK
Работает, но дает не предназначенный Optu?
Для меня очень важно то, что такая же инициализация не работает в списке-конструкторе-инициализации-списке, но работает в main
(с непредвиденным результатом)?