成员函数中的显式`this->` [英] Explicit `this->` in member functions

查看:101
本文介绍了成员函数中的显式`this->`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到推荐成员函数使用 this-> 显式地引用成员变量,以避免忘记声明成员变量和意外引用全局变量。任何人都可以评论,如果他们认为这是一个合理的预防措施或不必要的冗长,将不必要地使代码的阅读复杂化?

解决方案

由于我经常实现类模板,我习惯总是用 this-> 限定成员变量和成员函数。在类模板的上下文中还有另一个原因,为什么用 this-> 限定名称是有用的:不依赖于模板参数的名称只在阶段I查找,即,基类中的名称根据模板参数不会在基本中查找。通过用 this-> 限定成员名称,它们变得依赖。例如:

  #include< iostream> 

void f(){std :: cout<< :: f()\\\
; }

template< typename T>
class base
{
public:
void f(){std :: cout< base :: f()\\\
; }
};

template< typename T>
class derived
:public base< T>
{
public:
void g(){
f();
this-> f();
}
};

int main()
{
derived< int>()。
}

我使用 this-> 在所有我的代码,除非一些编码指南禁止这样做(我会考虑这方面的编码指南愚蠢和错误)。当然,在我自己的代码中,我限定所有可以限定的名称,并且不是自定义点(例如,我不会限定 swap())。 / p>

I have seen recommended that member functions refer to member variables using this-> explicitly, to avoid forgetting to declare the member variable and accidentally referring to a global variable. Can anyone comment if they think this is a reasonable precaution or unnecessary verbosity that will needlessly complicate the reading of the code? Does anybody actually do this in day-to-day real-life programming?

解决方案

Since I'm frequently implementing class templates, I'm used to always qualify member variables and member functions with this->. In the context of class templates there is another reason why it is useful to qualify names with this->: Names not depending on template arguments are looked up only in phase I look-up, i.e., names in base classes depending on template arguments are never looked up in the base. By qualifying member names with this-> they become dependent. For example:

#include <iostream>

void f() { std::cout << "::f()\n"; }

template <typename T>
class base
{
public:
    void f() { std::cout << "base::f()\n"; }
};

template <typename T>
class derived
    : public base<T>
{
public:
    void g() {
        f();
        this->f();
    }
};

int main()
{
    derived<int>().g();
}

I'm using qualification with this-> in all my code unless some coding guidelines prohibits me from doing so (and I'd consider this aspect of the coding guideline silly and wrong). Of course, in my own code I qualify all names which can be qualified and which aren't a customization point (e.g., I wouldn't qualify swap()).

这篇关于成员函数中的显式`this-&gt;`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆