成员的初始值(如"content(ht * wd, c)"C++ Primer 的构造函数中如何工作?

How the member's initial value like 'contents(ht * wd, c)' works in constructor function in C++ Primer?

本文关键字:构造函数 Primer C++ 何工作 工作 wd content ht 成员      更新时间:2023-10-16

我读过这本书C++入门。在第 7.3.1 节中:有一个Screen类的构造函数:

class Screen {
public:
typedef std::string::size_type pos;
Screen() = default; 
Screen(pos ht, pos wd, char c): height(ht), width(wd),
contents(ht * wd, c) { }
char get() const { return contents[cursor]; } 
inline char get(pos ht, pos wd) const;
Screen &move(pos r, pos c);
private:
pos cursor = 0;
pos height = 0, width = 0;
std::string contents;
};

在重载构造函数中:

Screen(pos ht, pos wd, char c): height(ht), width(wd),
contents(ht * wd, c) { }

contents(ht * wd, c)的初始值是多少,它是如何工作的?
在第 7.1.4 节中,有规定:

构造函数初始值设定项是成员名称的列表,每个成员名称后跟括号中的成员初始值(或在卷曲内( 大括号(。

而且我知道string有一种方法string s(n, 'c')初始化字符串,例如string s(10, 'c').
但是在构造函数成员初始化中使用string构造函数是如何工作的呢?
提前谢谢。

我在阅读本文时也遇到了这个问题。正如松元耀所指出的,我的猜测是,当我们在构造函数列表中使用括号或大括号时,编译器会自动调用每个类数据成员对应的构造函数来初始化函数参数。例如,在

Screen(pos ht, pos wd, char c): height(ht), width(wd), contents(ht * wd, c) { }

函数参数height,类型为int,初始化为int(ht);
函数参数width,类型为int,初始化为int(wd);
函数参数contents,类型为std::string,初始化为std::string(ht * wd, c);

如果我的答案不正确,请随时告诉我。

PS:感谢@M.M指出我的错误。