2

我读过《C++ Primer》这本书。在第 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构造函数成员初始化中利用构造函数呢?
提前致谢。

4

1 回答 1

1

在阅读有关此内容时,我也遇到了这个问题。正如宋元瑶所说,我的猜测是,当我们在构造函数列表中使用括号或花括号时,编译器会自动调用每个类数据成员对应的构造函数来初始化函数参数。例如,在

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:感谢@MM 指出我的错误。

于 2019-07-11T04:12:11.530 回答