![](/img/trans.png)
[英]Can we store the class object and not just the pointer to that object
[英]How do we store a reference to an object in the pointer?
我正在考虑此解决方案,但不确定是否正确。
Type* myObjP;
void setSmth(Type& toBePassed) {
myObjP = *toBePassed;
};
从句法上讲,您将需要使用:
void setSmth(Type& toBePassed) {
myObjP = &toBePassed; // Addressof operator rather than dereference operator.
}
使用这种机制时,取消引用myObjP
时必须非常小心。 如果传递给setSmth
的对象未myObjP
,则取消引用myObjP
将导致未定义的行为。
语言中有更强大的机制,但是如果没有其他上下文,很难提出任何建议。
toBePassed
是引用,而不是指针。 因此,您实际上需要&
运算符(运算符的地址),而不是*
运算符(取消引用运算符):
myObjP = &toBePassed;
注意:您实际上并没有将引用存储在指针中。 您只是存储指向所引用对象的常规指针。
你可以试试。 您应该使用&运算符来传递指向指针的地址。
double* myObjP;
void setSmth(double& toBePassed)
{
myObjP = &toBePassed;
};
int main()
{
double testValue{8.0};
setSmth(testValue);
if (testValue == *myObjP)
{
cout << "We store a reference to an object in the pointer\n";
cout << "testValue ==> " << testValue << " " << "*myObjP ==> " << *myObjP<<std::endl;
}
std::getchar();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.