c++ - 在 C++ 中使用 'this' 是一种好习惯吗?

标签 c++ coding-style

我想知道在 C++ 中使用“this”是否是一种好的做法。起初我以为我应该是因为这样你就可以清楚地表明你所指的是当前类的成员,但有时你会以这样的代码结尾:

Document::Document(QWidget *parent) : QWidget(parent)
{
    this->file = 0;
    this->layout = new QGridLayout(this);
    this->layout->setSpacing(2);
    this->layout->setMargin(0);
    this->setLayout(this.layout);
    this->textArea = new QTextEdit(this);
    this->textArea->setLineWrapMode(QTextEdit::NoWrap);
    this->textArea->setAcceptDrops(true);
    this->textArea->setAcceptRichText(true);
    this->textArea->setUndoRedoEnabled(true);
    this->textArea->setFont(QFont("Mono" , 11));
    this->layout->addWidget(this->textArea);
    this->textArea->show();
    this->textArea->setFocus();
}

我认为没有所有“this”会看起来好很多,特别是当它像 this->layout->addWidget(this.textArea); 那样使用时。而且我认为代码在大多数情况下应该使用相同的样式以使其更易于阅读,所以我应该在必要时使用“this”还是使用它来明确您引用的是一个好习惯同一类的成员。

最佳答案

对此没有唯一的答案。这取决于上下文,也取决于你问的是谁。

有些人一直使用this。有些人从不使用它。有些人改为使用特殊前缀重命名所有成员变量(mFile 而不是 file)。

我更愿意只在需要避免歧义时才使用 this 前缀。

在编写良好的代码中,您指的是局部变量还是成员变量通常很明显,因此 this 并没有做太多事情。但有时读者可能很难确定变量是否是类成员。那么 this 是澄清的好方法。

关于c++ - 在 C++ 中使用 'this' 是一种好习惯吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10310242/

相关文章:

C++错误: fields must have a constant size

vba - 面向对象风格 - 在哪里定义属性?编程语言

Java 枚举类型编码约定

coding-style - 有作者姓名的代码是绝对必要的吗?

python 风格 : inline function that needs no inlining?

c++ - Qt : how to include path with space in pro

C++Builder 10.2 基于函数的优化状态 "unknown attribute ' optimize' ignored"

c++ - 为什么我们使用 'this->' 而不是 'this.' 来访问成员?

c++ - 在俄语本地化的 Visual Studio 中构建时,编译器警告是乱码

android - 如何在Android gallery中制作一个像 "share menu"这样花哨的透明菜单?