C++ 无法使用字符串(大小、字符)构造函数
我有一个类C++ 无法使用字符串(大小、字符)构造函数,c++,string,c++11,constructor,C++,String,C++11,Constructor,我有一个类Screen,它使用std::string(size\t,char)构造函数初始化成员内容 #include <iostream> #include <string> struct Screen { friend std::ostream& print(std::ostream& os ,const Screen& screen); Screen() = default; Screen(std::size_t
Screen
,它使用std::string(size\t,char)
构造函数初始化成员内容
#include <iostream>
#include <string>
struct Screen {
friend std::ostream& print(std::ostream& os ,const Screen& screen);
Screen() = default;
Screen(std::size_t w, std::size_t h) :
width(w), height(h), content(w * h , ' ') {}
Screen(std::size_t w, std::size_t h, char c) :
width(w), height(h), content(w * h, c) {}
private:
std::size_t width = 24;
std::size_t height = 80;
std::size_t cursor = 0;
std::string content(width * height, ' ');
};
我从未使用过这种语法,但您似乎可以在类主体内初始化std::string,如下所示:
std::size_t width = 24;
std::size_t height = 80;
std::size_t cursor = 0;
std::string content{std::string( (width * height), ' ')};
您应该记住保持上述初始化顺序
代码的问题是,如果在构造函数初始化列表中初始化
内容
,编译器将不会执行变量定义中的初始化。因此,正如您在一条评论中所说的,您不能先进行默认初始化,然后在构造函数中覆盖它。以下内容修复了您的代码。我想需要在成员函数声明和成员数据定义之间消除一些歧义:
#include <iostream>
#include <string>
struct Screen {
friend std::ostream& print(std::ostream& os ,const Screen& screen);
Screen() = default;
Screen(std::size_t w, std::size_t h) :
width(w), height(h), content(w * h , ' ') {}
Screen(std::size_t w, std::size_t h, char c) :
width(w), height(h), content(w * h, c) {}
private:
std::size_t width = 24;
std::size_t height = 80;
std::size_t cursor = 0;
std::string content(width * height, ' ');
};
std::string content = std::string(width * height, ' ');
但我要做的不是在构造函数中重复我自己,而是使用委托构造函数和默认参数:
struct Screen
{
Screen(std::size_t w, std::size_t h, char c = ' ') :
width(w),
height(h),
content(w * h, c)
{}
Screen() :
Screen(24, 80)
{}
private:
std::size_t width;
std::size_t height;
std::string content;
};
完成了。为什么不使用初始值设定项列表来构造
std::string
?它试图初始化您在此处声明字符串的位置的目的是什么字符串内容((宽度*高度),“”)代码>?