这个构造函数是做什么的
What does this constructor do?
你能解释一下这些行吗?
class HasPtr {
public:
HasPtr(const std::string &s = std::string())://this line
ps(new std::string(s)), i(0) { } //and this
HasPtr(const HasPtr &p):
ps(new std::string(*p.ps)), i(p.i) { }
HasPtr& operator=(const HasPtr &);
~HasPtr() { delete ps; }
private:
std::string *ps;
int i;
};
这本书的主题是关于类的行为就像价值观。
在构造函数的声明中
HasPtr(const std::string &s = std::string())://this line
ps(new std::string(s)), i(0) { }
使用了默认参数CCD_ 1和mem初始值设定项列表
ps(new std::string(s)), i(0)
在将控件传递给构造函数主体之前执行的。由于在主体中没有任何操作,构造函数的主体是空的。
所以你可以调用构造函数而不需要像这样的参数
HasPtr obj;
在这种情况下,像string()
一样创建的空字符串将用作参数。
const std::string &s
是对std::string
常量实例的引用。
= std::string()
是默认值。xyz()
是xyz
的值初始化实例的语法。
因此,当HasPtr
在没有参数的情况下实例化时(例如HasPtr()
(,std::string()
0构造函数将被调用,s
绑定到临时空白std::string
实例(它一直存在到完整表达式的末尾,通常是第一个;
(。
然后用new std::string(s)
初始化ps
,在堆上复制s
,并在ps
中存储指向它的指针。
如果使用实际参数调用HasPtr
,则不会执行= std::string()
部分。
相关文章:
- 是什么让放置新调用对象的构造函数?
- 如果我真的真的想从 STL 容器继承,并且我继承构造函数并删除新运算符,会发生什么?
- 使用基类指针调用基类的值构造函数的语法是什么?
- 这个C++编译器优化(在自身的实例上调用对象自己的构造函数)的名称是什么,它是如何工作的?
- 构造函数后面的宏.什么意思?
- C++构造函数内部会发生什么?
- 用相同的参数声明两个构造函数的最偶像化的方法是什么?
- 如果在 C++ 构造函数中以错误的顺序初始化对象数据,会发生什么类型的错误
- 我是否为邪恶刽子手的构造函数错过了什么?
- 构造函数中没有参数的对象类成员按什么顺序初始化?
- 什么时候用指针调用C++类构造函数
- 这个构造函数是做什么的
- 将复制构造函数设置为private和=delete有什么区别
- 我不明白在这个例子中什么时候调用构造函数
- 在C++中,从构造函数中将字符串文本分配给成员const char*变量时会发生什么
- c++ 17 中结构自动定义构造函数的规则是什么?
- 在C++中初始化带有和不使用构造函数调用的对象有什么区别
- 指示汇编时间叫什么构造函数
- 在这种情况下调用什么构造函数
- 使用什么构造函数