我对 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/