成员的初始值(如"content(ht * wd, c)"C++ Primer 的构造函数中如何工作?
How the member's initial value like 'contents(ht * wd, c)' works in constructor function in C++ Primer?
我读过这本书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指出我的错误。
相关文章:
- "error: no matching function for call to"构造函数错误
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 选择要调用的构造函数
- 如何委托派生类使用其父构造函数?
- 构造函数正在调用一个使用当前类类型的函数
- 没有用于初始化C++中的变量模板的匹配构造函数
- 初始化具有非默认构造函数的std::数组项的更好方法
- 当从函数参数中的临时值调用复制构造函数时
- 在c++构造函数中使用随机字符串生成器
- 一对向量构造函数:初始值设定项列表与显式构造
- 从构造函数抛出异常时如何克服内存泄漏
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 具有默认模板类型的默认构造函数的类型推导
- 使用dynamic_cast和构造函数时出错
- 在c++中使用向量时,如何调用构造函数和析构函数
- 成员的初始值(如"content(ht * wd, c)"C++ Primer 的构造函数中如何工作?