C++ Passing `this` into method by reference
I have a class constructor that expects a reference to another class object to be passed in as an argument. I understand that references are preferable to pointers when no pointer arithmetic will be performed or when a null value will not exist.
This is the header declaration of the constructor:
class MixerLine {
private:
MIXERLINE _mixerLine;
public:
MixerLine(const MixerDevice& const parentMixer, DWORD destinationIndex);
~MixerLine();
}
This is the code that calls the constructor (MixerDevice.cpp):
void MixerDevice::enumerateLines() {
DWORD numLines = getDestinationCount();
for(DWORD i=0;i<numLines;i++) {
MixerLine mixerLine( this, i );
// other code here removed
}
}
Compilation of MixerDevice.cpp fails with this error:
Error 3 error C2664: 'MixerLine::MixerLine(const MixerDevice &,DWORD)' : cannot convert parameter 1 from 'MixerDevice *const ' to 'const MixerDevice &'
But I thought pointer values could be assigned to pointers, eg
Foo* foo = new Foo();
Foo& bar = foo;
this
是一个指针,要得到一个引用,你必须解除引用( *this
)它:
MixerLine mixerLine( *this, i );
You should dereference this
, because this
is a pointer, not a reference. To correct your code you should write
for(DWORD i=0;i<numLines;i++) {
MixerLine mixerLine( *this, i ); // Ok, this dereferenced
// other code here removed
}
Note: the second const
at the constructor's parameter const MixerDevice& const parentMixer
is completely useless.
To obtain a reference from a pointer you need to dereference the pointer, as it has already been mentioned. Additionally (maybe due to copying into the question?) the constructor should not compile:
const MixerDevice& const parentMixer
That is not a proper type, references cannot be const qualified, only the referred type can be, so the two (exactly equivalent) options are:
const MixerDevice& parentMixer
MixerDevice const& parentMixer
(Note that the const
qualifying of MixerDevice
can be done at either way, and it means exactly the same).
上一篇: 通过引用或指针返回并检查null?
下一篇: C ++通过引用将`this`传入方法