gpt4 book ai didi

c++ - 这个构造函数做什么?

转载 作者:行者123 更新时间:2023-11-30 01:01:34 25 4
gpt4 key购买 nike

你能解释一下这些行吗?

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) { }

使用了默认参数 std::string() 和 mem-initializer 列表

ps(new std::string(s)), i(0)

在控件将传递给构造函数主体之前执行。由于主体中无事可做,因此构造函数的主体为空。

所以你可以在没有参数的情况下调用构造函数

HasPtr obj;

在这种情况下,像 string() 这样创建的空字符串将用作参数。

关于c++ - 这个构造函数做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58913074/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com