[英]Cpp/ C++ unique Pointer on objects access functions of that class
How do I access functions via a unique pointer pointing on an object 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 has a constructor with an int as argument, getY()
just prints out that int value. foo 有一个以 int 作为参数的构造函数,
getY()
只是打印出该 int 值。
Obviously foo f1(1); f1.getY();
显然
foo f1(1); f1.getY();
foo f1(1); f1.getY();
works but idk how to acces getY()
over the pointer.有效,但不知道如何通过指针访问
getY()
。 unique_ptr<foo> ptr1 = make_unique<foo>(2); *ptr1.getY();
was my initial idea, but it doesn't work.是我最初的想法,但它不起作用。
You can use it as an ordinary pointer.您可以将其用作普通指针。 For example
例如
( *ptr1 ).getY();
or或者
ptr1->getY();
Or even like:)甚至喜欢:)
p.get()->getY();
( *p.get() ).getY();
That is there are declared the following operators and the accessor in the class template unique_ptr
即在 class 模板
unique_ptr
中声明了以下运算符和访问器
add_lvalue_reference_t<T> operator*() const;
pointer operator->() const noexcept;
pointer get() const noexcept;
The problem is that due to operator precedence when you wrote *ptr1.getY();
问题是由于您编写
*ptr1.getY();
时的运算符优先级; , it was equivalent to writing: ,相当于写:
*(ptr1.getY());
So this means you're trying to call a member function named getY
on the smart pointer ptr1
but since ptr1
has no member function called getY
you get the error.所以这意味着你试图在智能指针
ptr1
上调用一个名为getY
的成员 function 但由于ptr1
没有名为getY
的成员 function 你会得到错误。
To solve this you should write:为了解决这个问题,你应该写:
( *ptr1 ).getY();//works now
This time you're specifically asking/grouping *ptr
together and then calling the member function getY
on the resulting object.这次您专门询问/将
*ptr
组合在一起,然后在生成的 object 上调用成员 function getY
。 And since the resulting object is of type foo
which has a member function getY
, this works.并且由于生成的 object 是
foo
类型,它有一个成员 function getY
,所以这是可行的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.