c++ - 如何在 C++ 中传递 "this"

标签 c++

我对 C++ 中的 this 关键字感到困惑,我不确定传递 this 是否正确。这是我正在努力解决的一段代码:

ClassA::ClassA( ClassB &b) {

    b.doSth(this);
    // trying to call b's routine by passing a pointer to itself, should I use "this"?
}

ClassB::doSth(ClassA * a) {
       //do sth
}

最佳答案

您使用正确。 this 指针指向当前对象实例。

class helper 
{
public:
     void help(worker *pWorker) {
          //TODO do something with pWorker . . .
     }

     void help2(worker& rWorker) {
          //TODO do something with rWorker . . .
     }
};

class worker 
{
public:
     void dowork() {
          //this one takes a worker pointer so we can use the this pointer.
          helper.help(this);

          //to pass by reference, you need to dereference the this pointer.
          helper.help2(*this);
     }
     helper helper;
};

另外,假设你声明了 worker *pW = new worker()。如果您在 pW 对象上调用其中一种方法(dowork),您会注意到 this 指针和 pW 具有完全相同的值(它们都是相同的地址)。

(尚未对其进行测试以确保它可以构建,但我认为应该)。

关于c++ - 如何在 C++ 中传递 "this",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1823816/

相关文章:

c++ - C++ 中 QVariants 的使用和 QML 中的属性

android - "Serializing CDT Project settings"-- Eclipse 错误

c++ - 在哪里放置全局域特定常量(以及如何放置)?

c++ - 如何在 C++ 中进行多线程文件处理?

c# - 来自 Windows 服务的屏幕截图

c++ - boost 如何避免 32 位机器上的 ABA 问题?

java - 在我的 Android 应用程序中使用 ffmpeg.c

c++ - 重载抽象虚方法返回模板参数 T& 作为具体参数 short*&

C++ 类不是自身的基础

c++ - SWIG, boost 共享指针和继承