[英]Cpp/ C++ unique Pointer on objects access functions of that class
如何通过指向 class 的 object 的唯一指针访问函数
struct foo
{
foo(int);
void getY();
};
int main()
{
foo f1(1);
f1.getY();
std::unique_ptr<foo> ptr1 = make_unique<foo>(2);
*ptr1.getY(); // Error
};
foo 有一个以 int 作为参数的构造函数, getY()
只是打印出该 int 值。
显然foo f1(1); f1.getY();
foo f1(1); f1.getY();
有效,但不知道如何通过指针访问getY()
。 unique_ptr<foo> ptr1 = make_unique<foo>(2); *ptr1.getY();
是我最初的想法,但它不起作用。
您可以将其用作普通指针。 例如
( *ptr1 ).getY();
或者
ptr1->getY();
甚至喜欢:)
p.get()->getY();
( *p.get() ).getY();
即在 class 模板unique_ptr
中声明了以下运算符和访问器
add_lvalue_reference_t<T> operator*() const;
pointer operator->() const noexcept;
pointer get() const noexcept;
问题是由于您编写*ptr1.getY();
时的运算符优先级; ,相当于写:
*(ptr1.getY());
所以这意味着你试图在智能指针ptr1
上调用一个名为getY
的成员 function 但由于ptr1
没有名为getY
的成员 function 你会得到错误。
为了解决这个问题,你应该写:
( *ptr1 ).getY();//works now
这次您专门询问/将*ptr
组合在一起,然后在生成的 object 上调用成员 function getY
。 并且由于生成的 object 是foo
类型,它有一个成员 function getY
,所以这是可行的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.