【问题标题】:What is the difference between this->variable and namespace::class::variable in C++?C++ 中 this->variable 和 namespace::class::variable 有什么区别?
【发布时间】:2023-04-07 06:37:02
【问题描述】:

考虑一下:

我有一个包含一些私有变量和一些公共方法的类,例如设置器或构造器。当我实现这些方法时,说this->variable = 0;namespace::class::variable = 0; 有什么区别吗?

在标题(example.h)中:

namespace spc
{
    class MyClass
    {
     public:
            MyClass();
     private:
            int variable;
            int variable2;
    };
}

现在在 cpp 文件 (example.cpp) 我有:

spc::MyClass::MyClass()
{
     spc::MyClass::variable = 0;
     this->variable2 = 0;
}

这将编译。而且在应用程序源代码中,此类的构造和对象都将具有值为 0 的变量(假设我也有一些 getter)。所以我的问题是:这两行代码有什么不同吗?

【问题讨论】:

  • 两者都不需要。
  • 那么如何给成员变量赋值呢?只是说'variable=0;'?
  • 是的,只要你在一个成员函数中或者变量是公共的

标签: c++ class oop namespaces this


【解决方案1】:

这将编译

spc::MyClass::variable = 0;
this->variable2 = 0;

没错!但这也会编译,产生相同的结果:

variable = 0;
variable2 = 0;

一般来说,this-> 和作用域解析:: 运算符可以让您在有任何歧义时指示编译器使用哪个变量。例如,构造函数参数可能与成员变量同名:

spc::MyClass::MyClass(int variable2)
{
     this->variable2 = variable2;
}

这里,this-> 的使用区分 variable2-the-parameter 和 variable2-the-member of spc::MyClass

然而,在没有歧义的情况下,使用“简单”的变量名对于该语言来说是“惯用的”。

注意:MyClass::somethingthis->something 之间的一个区别是当某事物是虚拟成员函数时;前者会抑制虚拟调用机制,而后者不会(感谢 Sebastian Redl 的精彩评论)。

【讨论】:

    【解决方案2】:

    以下语句是等价的:

    spc::MyClass::MyClass()
    {
        // Very uncommon
        spc::MyClass::variable = 0;
    
        // Use this for clarity, if you feel the need
        this->variable = 0;
    
        // Short and common
        variable = 0;
    }
    

    【讨论】:

      【解决方案3】:

      this->variable 导致在当前类的范围内查找名称。

      MyClass::variable 导致在MyClass 范围内查找名称。

      在这种情况下,当前类是MyClass,因此两者都等价于不合格的variable

      在其他情况下,它们可能不是。例如,Base::member 可能引用基类的成员,而在派生类的成员函数中,this->member 可能引用隐藏基类成员的派生类成员。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-11-16
        • 2021-08-19
        • 1970-01-01
        • 1970-01-01
        • 2013-07-22
        • 2013-12-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多