c++ - 在 C++ 中调用内部类成员的情况下是否应该使用 -> 运算符?

标签 c++

我的问题是关于C++中的这个运算符,我们应该尽可能多地使用它吗?我给出了以下示例来说明我的观点:

class Abc

{
public:
  int a_;
  void fun();

};

void Abc::fun()
{
  // option 1
   a_ = 3;
  // option 2
  this->a_ = 3;
}

在函数类成员fun()中,我们可以通过两种方式调用成员变量,一种是使用this->,另一种是不使用。所以我的问题是:鼓励哪种做法?谢谢。

最佳答案

在一般情况下,两者都可以使用是对的。在这种情况下,这只是风格问题,正确的做法是遵循项目的风格指南。在这方面,一致性比个人喜好更重要。

但是,在两种情况下使用 this-> 会有所不同。一种是当成员函数有一个与成员同名的参数时;在这种情况下,参数的名称隐藏了成员的名称,您必须使用 this-> 来引用成员(@Krypton 的回答首先指出):

void Abc::fun(int a_)
{
  a_ = 3;  // assigns into the parameter
  this->a_ = 3;  // assigns into the data member
}

另一种情况是当您在类模板中工作时,成员是从基类继承的,基类取决于您的类模板的模板参数。在这种情况下,非限定查找不会搜索相关上下文,因此不会找到该成员。使用 this-> 将访问转换为依赖表达式,它将在实例化时查找,从而正确解析为成员。示例:

template <class T>
struct Base
{
protected:
  T a_;
};


template <class T>
struct Abc : Base<T>
{
  void fun() {
    a_ = 3;  // error, not `a_` in scope
    this->a_ = 3;  // OK, found at instantiation time
  }
};

在这种情况下,存在另一种解决方案:使名称明确可见:

template <class T>
struct Abc : Base<T>
{
protected:
  using Base<T>::a_;

public:
  void fun() {
    a_ = 3;  // OK, found thanks to `using` declaration
  }
};

关于c++ - 在 C++ 中调用内部类成员的情况下是否应该使用 -> 运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25862082/

相关文章:

c++ - 铛++ : fatal error: 'unistd.h' file not found

c++ - 使用 'assert' 验证参数数量

c++ - 引用临时成员

c++ - 模板化显式转换运算符

c++ - 如何找到数组组的最大值

c++ - 尝试使用 glfw 和 bgfx 运行基本程序时出现 LNK2001 无法解析的外部符号 __imp_calloc

c++ - 如何在C++中获取正则表达式的底层字符串?

c++ - C/C++ 内存泄漏(使用 PCRE)

c++ - 将 std::vector 复制到 qvector

c++ - 如何将 CString 传递给格式字符串 %s?