gpt4 book ai didi

c++ - this->field 与 C++ 中的 this.field

转载 作者:行者123 更新时间:2023-11-30 01:01:53 31 4
gpt4 key购买 nike

假设 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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com