我想问一个关于 C++ 中的引用和指针的问题。
我是 C++ 的初学者,所以如果答案是微不足道的,我深表歉意。
作为教程的一部分,我编写了以下代码。
#include <iostream>
using namespace std;
class Deep {
private:
int *data;
public:
void set_data_value(int d) {*data = d;}
int get_data_value () {return *data;}
// Constructor
Deep (int d);
// Copy constructor
Deep (const Deep &source);
// Destructor
~Deep();
};
Deep::Deep(int d) {
data = new int;
*data = d;
}
Deep::Deep (const Deep &source)
: Deep (*source.data){ // main body of the constructor (delegation comes before the body)
cout << "Copy Constructor - deep copy" << endl;
}
Deep::~Deep() {
delete data;
cout << "Destructor deleting data" << endl;
}
void display_deep (Deep s) {
cout << s.get_data_value() << endl;
}
int main () {
Deep obj1 {100};
display_deep (obj1);
Deep obj2{obj1};
obj2.set_data_value(1000);
cout << endl;
return 0;
}
此代码有效。我将解释我所做的:我定义了一个名为
Deep
的类练习深拷贝。名为 data
的指针是私有(private)的,我已经包含(后来定义)了函数原型(prototype) set_data_value
和 get_data_value
.set_data_value
接受整数 d
, 取消引用 data
并赋值 d
给它。get_data_value
简单地返回 data
的取消引用值.在
public
domain 还有一个构造函数接受一个整数 d
, 一个复制构造函数,它保持对象不变并接受引用 &source
旁边有一个析构函数。在复制构造函数中,我使用委托(delegate)构造函数来改进代码流。
但是,如果我们观察复制构造函数
Deep::Deep (const Deep &source)
: Deep (*source.data){ // main body of the constructor (delegation comes before the body)
cout << "Copy Constructor - deep copy" << endl;
}
我们知道这是根据 void display_deep (Deep s)
的值传递性质运行的。 , 所以 source
是对我们的 s
的引用传入。然后我们指向source
并以某种方式获取数据的值,然后将其传递给构造函数。这是如何运作的?是否
*source.data
像我描述的那样工作还是编译器采取不同的路线?
最佳答案
We then point to source and
没有指向任何东西。在这一行:
: Deep (*source.data)
您只是访问 data
里面 source
.然后你取消引用它。就像你取消引用 *data
获取其中的值(value)。
关于c++ - C++ 类上下文中的引用和指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63328506/