[英]C++ Passing `this` into method 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 的編譯失敗並出現以下錯誤:
錯誤 3 錯誤 C2664:“MixerLine::MixerLine(const MixerDevice &,DWORD)”:無法將參數 1 從“MixerDevice *const”轉換為“const MixerDevice &”
但我認為指針值可以分配給引用,例如
Foo* foo = new Foo();
Foo& bar = foo;
this
是一個指針,要獲得引用,您必須取消引用 ( *this
) 它:
MixerLine mixerLine( *this, i );
您應該取消引用this
,因為this
是一個指針,而不是引用。 要更正您的代碼,您應該編寫
for(DWORD i=0;i<numLines;i++) {
MixerLine mixerLine( *this, i ); // Ok, this dereferenced
// other code here removed
}
注意:構造函數的參數const MixerDevice& const parentMixer
中的第二個const
完全沒用。
如前所述,要從指針獲取引用,您需要取消對指針的引用。 另外(可能是由於復制到問題中?)構造函數不應編譯:
const MixerDevice& const parentMixer
那不是正確的類型,引用不能是 const 限定的,只有被引用的類型可以是,所以兩個(完全等價的)選項是:
const MixerDevice& parentMixer
MixerDevice const& parentMixer
(請注意, MixerDevice
的const
限定可以用任何一種方式完成,它的含義完全相同)。
指針值可以分配給指針,但不能分配給引用! 1個
Foo* foo = new Foo();
Foo& bar = *foo;
^
^
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.