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

标签 c++ pointers operators this field

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

相关文章:

c++ - C++ 的 auto 关键字是否促进了草率的编程,或者它是否有原则性的用途?

c++ - 在 C++ 中从原型(prototype)调用函数

c++ - 尝试将指针与结构一起使用时出错

C++ 内存泄漏 - 我应该删除什么,在哪里删除?

c - x++ 的增量操作何时发生?

c++ - 这是什么意思 "->"?

c++ std::forward 在容器上调用 operator[]

c++ - Getter 返回 null C++

c - c中释放指针后如何保存指针地址

c# - C# 中的 IS NOT 运算符