gpt4 book ai didi

c++ - 带有结构指针的类初始化列表

转载 作者:行者123 更新时间:2023-11-27 22:51:41 24 4
gpt4 key购买 nike

我正在看一个 PIMPL 习语的例子,我发现了一行我真的不明白的代码。由于我是 c++ 和 OOP 的新手,我希望有人能解释这个函数的作用。

有人可以阐明这个功能吗?

PublicClass::PublicClass(const PublicClass& other)
: d_ptr(new CheshireCat(*other.d_ptr)) { // <------- This line
// do nothing
}

/

这是例子。

//header file:
class PublicClass {
public:
PublicClass(); // Constructor
PublicClass(const PublicClass&); // Copy constructor
PublicClass(PublicClass&&); // Move constructor
PublicClass& operator=(const PublicClass&); // Copy assignment operator
~PublicClass(); // Destructor
// Other operations...

private:
struct CheshireCat; // Not defined here
unique_ptr<CheshireCat> d_ptr; // opaque pointer
};

/

//CPP file:
#include "PublicClass.h"

struct PublicClass::CheshireCat {
int a;
int b;
};

PublicClass::PublicClass()
: d_ptr(new CheshireCat()) {
// do nothing
}

PublicClass::PublicClass(const PublicClass& other)
: d_ptr(new CheshireCat(*other.d_ptr)) {
// do nothing
}

PublicClass::PublicClass(PublicClass&& other)
{
d_ptr = std::move(other.d_ptr);
}

PublicClass& PublicClass::operator=(const PublicClass &other) {
*d_ptr = *other.d_ptr;
return *this;
}

PublicClass::~PublicClass() {}

最佳答案

结构不“取值”。 函数接受值。构造函数是函数。在 new CheshireCat(*other.d_ptr) ,您调用 CheshireCat编译器生成的复制构造函数 .

您还传递的不是指针而是一个引用,因为您取消了对other.d_ptr 的引用。通过重载 operator*std::unique_ptr .事实上,如果你写了 new CheshireCat(other.d_ptr)new CheshireCat(other.d_ptr.get()) , 那么你会得到一个编译错误。

关于c++ - 带有结构指针的类初始化列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36628694/

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