C++ 通过引用将 `this` 传递给方法

标签 c++ reference pass-by-reference

我有一个类构造函数,它希望将对另一个类对象的引用作为参数传入。我知道当不执行指针运算或空值不存在时,引用优于指针。

这是构造函数的头部声明:

class MixerLine {

private:
    MIXERLINE _mixerLine;
    
public:

    MixerLine(const MixerDevice& const parentMixer, DWORD destinationIndex); 

    ~MixerLine();
}

这是调用构造函数的代码(MixerDevice.cpp):

void MixerDevice::enumerateLines() {
    
    DWORD numLines = getDestinationCount();
    for(DWORD i=0;i<numLines;i++) {
        
        MixerLine mixerLine( this, i );
        // other code here removed
    }
}

MixerDevice.cpp 的编译失败并出现此错误:

Error 3 error C2664: 'MixerLine::MixerLine(const MixerDevice &,DWORD)' : cannot convert parameter 1 from 'MixerDevice *const ' to 'const MixerDevice &'

但我认为指针值可以分配给引用,例如

Foo* foo = new Foo();
Foo& bar = foo;

最佳答案

this 是一个指针,要获得引用,您必须取消引用 (*this) 它:

MixerLine mixerLine( *this, i );

关于C++ 通过引用将 `this` 传递给方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11170440/

相关文章:

c++ - 在 CMake 项目中从 C++ 调用 C 代码。 undefined symbol 。有外部C

c++ - 在构造函数中初始化引用

pointers - 如何在 Go 中将服务指针从一个包传递到另一个包?

java - Java 是否通过引用传递?

c++ - LLVM IR 中 bool 的数据类型

c++ - 将类数组传递给函数

c# - .NET 程序集依赖项

javascript - 如何在不使用 Javascript 调用它的情况下将参数传递给引用的函数

python - 如何通过引用将切片传递给函数

c++ - 在 C++11 中初始化字符串列表