这个构造函数是做什么的

What does this constructor do?

本文关键字:什么 构造函数      更新时间:2023-10-16

你能解释一下这些行吗?

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()部分。