假设 this
是一个指针,(2)
和 (3)
行如何在下面的 C++ 类中编译,所以应该需要 ->
符号来访问字段(如 (1)
行所示)? ( Source )
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
template <typename T>
class sptr_wrapper
{
private:
boost::shared_ptr<T> sptr;
public:
template <typename ...ARGS>
explicit sptr_wrapper(ARGS... a)
{
this->sptr = boost::make_shared<T>(a...);
}
explicit sptr_wrapper(boost::shared_ptr<T> sptr)
{
this->sptr = sptr; // (1)
}
virtual ~sptr_wrapper() noexcept = default;
void set_from_sptr(boost::shared_ptr<T> sptr)
{
this.sptr = sptr; // (2)
}
boost::shared_ptr<T> get_sptr() const
{
return sptr; // (3)
}
};
最佳答案
(2)
行无效。正如你所说,this
是一个指针,我们需要使用->
而不是。
作为class template的成员| , sptr_wrapper::set_from_sptr
不需要被实例化,直到它被使用。所以您可以添加一些代码来尝试调用它,然后您可能会如预期的那样得到编译错误。
This applies to the members of the class template: unless the member is used in the program, it is not instantiated, and does not require a definition.
(3)
行有效; sptr
指的是成员sptr
,与this->sptr
作用相同.
When a non-static class member is used in any of the contexts where the this keyword is allowed (non-static member function bodies, member initializer lists, default member initializers), the implicit
this->
is automatically added before the name, resulting in a member access expression (which, if the member is a virtual member function, results in a virtual function call).
关于c++ - this->field 与 C++ 中的 this.field,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57583612/