在对象中使用或不使用'this'
Use or don't use 'this' within a object
我的问题是指当我想调用同一类的其他方法时的情况。用和不用"this"有什么区别?类的变量也是如此。通过"this"访问这些变量有区别吗?是否与这些方法/变量是私有的/公共的有关?例子:
class A {
private:
int i;
void print_i () { cout << i << endl; }
public:
void do_something () {
this->print_i(); //call with 'this', or ...
print_i(); //... call without 'this'
this->i = 5; //same with setting the member;
i = 5;
}
};
一般来说,这是一个风格问题。所有我去过的地方工作人员不喜欢使用this->
,除非当必要的。
在某些情况下,它是有区别的:
int func();
template <typename Base>
class Derived : public Base
{
int f1() const
{
return func(); // calls the global func, above.
}
int f2() const
{
return this->func(); // calls a member function of Base
}
};
在这种情况下,this->
使函数的名称依赖,这反过来又将绑定延迟到模板是什么时候实例化。如果没有this->
,则函数名为在模板定义时绑定,而不考虑什么可能是在Base
(因为不知道模板是什么时候)定义)。
根本没有功能差异。但有时你需要显式地包含this
作为对编译器的提示;例如,如果函数名本身有歧义:
class C
{
void f() {}
void g()
{
int f = 3;
this->f(); // "this" is needed here to disambiguate
}
};
James Kanze的回答还解释了一种情况,即显式使用this
会改变编译器选择重载名称的版本。
相关文章:
- 创建具有 new in 函数和"this is nullptr"异常的对象
- 在什么情况下,两个堆栈分配的结构对象的 this 点指向同一个地址?
- QObject::连接无法将信号连接到*this*对象的插槽
- "this"指针的值在对象的生存期内是否恒定?
- 通过从构造函数中的'this'复制的指针改变常量对象
- "this"指向的对象是否与 const 对象相同?
- 将"this"传递给子对象
- 对于琐碎的对象,在"this"上调用新放置是否安全?
- 如何将"this"的生命周期移动到C++中的另一个对象中?
- 是 *this = Ctor();清除对象状态的合法和高效?
- 删除指针后阻止对象使用 "this"
- 返回C++"This"对象的函数
- GCC:当层次结构中存在虚拟继承时,C++11 内联对象初始化(使用 "this")不起作用
- 通过"this"访问另一个对象的定义?
- 对象的"this"指针是否等于指向其(单个)基类的指针?
- C++:将数组传递给构造函数并将其保存在 this 对象中
- 如何从"this"对象本身内部将shared_ptr返回到当前对象
- C++static_cast添加常量和"this"对象的const_cast有什么区别?
- 获取"this"对象到另一个函数的shared_ptr:给出运行时异常
- 声明指向*this*对象的指针的优点或理由是什么?