I have a program that simulates a window; So I have the content of the window stored in a member data content which is a std::string type:
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;
}
AS you can see above I couldn't initialize the member content with curly-braces-initializer-list which the compiler complains about "narrowing type". But it works with "Direct initialization".
- 
Why I cannot use Curly-brace-initialization-list above in the Constructor-initializer-list to invoke
std::string(size_t count, char). - 
Why this
std::string str{5u, '*'}; // compiles but not OKWorks but gives not intended ouptu? - 
The thing that matters me a lot is why the same initialization doesn't work on constructor-member-initialization-list but works in
main(with not intended result)? 
Aucun commentaire:
Enregistrer un commentaire