c++ - C++ 类上下文中的引用和指针

标签 c++ pointers reference

我想问一个关于 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_valueget_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/

相关文章:

c++ - 带有 msvc140 的通用 lambda

C中按值调用函数

c - 将从文件中读取的不同字符串插入到链接列表中

rust - 在模式匹配中借用

c# - 如何枚举给定根对象的所有可到达对象?

java - 每当我添加一个对象时,它就会出现在屏幕的一角

c++ - C++ 中的根基类

c++ - 有没有办法从构建脚本输出中解析依赖树?

c++ - 如何确保 Qt Widget.repaint 已完成运行?

c - strlen 指针与数组