初始化类C ++中的引用成员 [英] Initialize reference member in class C++
问题描述
我在一个类中有一个参考成员,如下所示:
I have a class in which I have a reference member as follows:
SampleClass.h
class SampleClass{
public:
SampleClass(bool mirror=false);
void updateFunction();
private:
BodyTrackeDevice _device;
BodyBlob& _userBody;
BodyMuscle _muscle;
bool _mirror;
};
SampleClass.cpp
SampleClass::SampleClass(bool mirror)
{
this->_mirror = mirror;
}
错误:
SampleClass
必须显式初始化引用成员_userBody
Error: Constructor for
SampleClass
must explicitly initialize the reference member_userBody
这很明显,因为我应该做的初始化引用成员的操作应该是
which is obvious because what I should have done to initialise the reference member should have been
SampleClass::SampleClass(bool mirror, BodyBlob& bodyBlob) : _userBody(bodyBlob){
...
}
但是, BodyBlob&
是我从 BodyTrackerDevice
中得到的,作为 BodyTrackerDevice.getTrackedBody [0]
并不是我可以传递给类的构造函数的东西。
However, BodyBlob&
is something that I'll be getting from BodyTrackerDevice
as BodyTrackerDevice.getTrackedBody[0]
and is not something that I can pass to the constructor of the class. What is the right approach followed here to get rid of the error?
推荐答案
引用基本上就像指针,但有两个非常重要的地方,那就是正确的方法来消除错误?区别:a)它们必须在创建时进行初始化(以最大程度地减少与悬挂指针相比悬挂参考的可能性),以及b)无法更改它们指向的对象。
References are basically like pointers, but with two very important difference: a) they must be initialized when created (in order to minimize the possibility of having a dangling references in contrast to a dangling pointer), and b) cannot change the object they point to.
在您的代码中,您有b)可能满足的需求,但对于a)没有(您说您将获得_userBody稍后的值,而不是在构建对象),因此只剩下两种可能性:使用简单的对象(可以通过复制新值进行初始化)[不是很好],或者仅使用指针而不是引用。
In your code, you have the needs that maybe can be covered by b), but not for a)(you say you'll get the value for _userBody "later", not in the time of building the object), so the you've only two possibilities left: use a simple object (which you can initialize by copying the new value) [not very good], or just use a pointer instead of a reference.
class SampleClass {
public:
SampleClass(bool mirror=false);
void updateFunction();
private:
BodyTrackeDevice _device;
BodyBlob * _userBody;
BodyMuscle _muscle;
bool _mirror;
};
SampleClass::SampleClass(bool mirror)
{
this->_mirror = mirror;
}
void SampleClass::updateFunction()
{
_userBody = &( device.getTrackedBody[ 0 ] );
}
希望这会有所帮助。
这篇关于初始化类C ++中的引用成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!