C++ 我什么时候应该明确使用“this”指针?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/993352/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
When should I make explicit use of the `this` pointer?
提问by ASk
When should I explicitly write this->member
in a method of
a class?
我什么时候应该明确地写this->member
一个类的方法?
回答by ASk
Usually, you do not have to, this->
is implied.
通常,您不必这样做,this->
是隐含的。
Sometimes, there is a name ambiguity, where it can be used to disambiguate class members and local variables. However, here is a completely different case where this->
is explicitly required.
有时,存在名称歧义,可用于消除类成员和局部变量的歧义。但是,这是一个完全不同的情况,其中this->
明确要求。
Consider the following code:
考虑以下代码:
template<class T>
struct A {
int i;
};
template<class T>
struct B : A<T> {
int foo() {
return this->i;
}
};
int main() {
B<int> b;
b.foo();
}
If you omit this->
, the compiler does not know how to treat i
, since it may or may not exist in all instantiations of A
. In order to tell it that i
is indeed a member of A<T>
, for any T
, the this->
prefix is required.
如果省略this->
,编译器不知道如何处理i
,因为它可能存在也可能不存在于A
. 为了告诉它i
确实是 的成员A<T>
,对于 any T
,this->
需要前缀。
Note: it is possible to still omit this->
prefix by using:
注意:仍然可以this->
使用以下方法省略前缀:
template<class T>
struct B : A<T> {
using A<T>::i; // explicitly refer to a variable in the base class
int foo() {
return i; // i is now known to exist
}
};
回答by PaV
If you declare a local variable in a method with the same name as an existing member, you will have to use this->var to access the class member instead of the local variable.
如果在与现有成员同名的方法中声明局部变量,则必须使用 this->var 来访问类成员而不是局部变量。
#include <iostream>
using namespace std;
class A
{
public:
int a;
void f() {
a = 4;
int a = 5;
cout << a << endl;
cout << this->a << endl;
}
};
int main()
{
A a;
a.f();
}
prints:
印刷:
5
4
5
4
回答by avakar
There are several reasons why you might need to use this
pointer explicitly.
您可能需要this
显式使用指针的原因有多种。
- When you want to pass a reference to your object to some function.
- When there is a locally declared object with the same name as the member object.
- When you're trying to access members of dependent base classes.
- Some people prefer the notation to visually disambiguate member accesses in their code.
- 当您想将对象的引用传递给某个函数时。
- 当存在与成员对象同名的本地声明对象时。
- 当您尝试访问依赖基类的成员时。
- 有些人更喜欢用这种表示法在他们的代码中直观地消除成员访问的歧义。
回答by zebrabox
- Where a member variable would be hidden by a local variable
- If you just want to make it explictly clear that you are calling an instance method/variable
- 成员变量将被局部变量隐藏的地方
- 如果您只是想明确说明您正在调用实例方法/变量
Some coding standards use approach (2) as they claim it makes the code easier to read.
一些编码标准使用方法 (2),因为他们声称它使代码更易于阅读。
Example:
Assume MyClass has a member variable called 'count'
示例:
假设 MyClass 有一个名为“count”的成员变量
void MyClass::DoSomeStuff(void)
{
int count = 0;
.....
count++;
this->count = count;
}
回答by Brad Robinson
Although I usually don't particular like it, I've seen others use this-> simply to get help from intellisense!
虽然我通常不是特别喜欢它,但我看到其他人使用它-> 只是为了从智能感知中获得帮助!
回答by John Dibling
There are few cases where using this
mustbe used, and there are others where using the this
pointer is one way to solve a problem.
很少有this
必须使用using 的情况,而在其他情况下,使用this
指针是解决问题的一种方法。
1) Alternatives Available: To resolve ambiguity between local variables and class members, as illustrated by @ASk.
1)可用的替代方案:解决局部变量和类成员之间的歧义,如@ASk 所示。
2) No Alternative:To return a pointer or reference to this
from a member function. This is frequently done (and should be done) when overloading operator+
, operator-
, operator=
, etc:
2) No Alternative:this
从成员函数返回指针或引用。这是经常做(和应该做)超载时operator+
,operator-
,operator=
,等:
class Foo
{
Foo& operator=(const Foo& rhs)
{
return * this;
}
};
Doing this permits an idiom known as "method chaining", where you perform several operations on an object in one line of code. Such as:
这样做允许一种称为“方法链”的习惯用法,您可以在一行代码中对一个对象执行多个操作。如:
Student st;
st.SetAge (21).SetGender (male).SetClass ("C++ 101");
Some consider this consise, others consider it an abomination. Count me in the latter group.
一些人认为这是 consise,其他人认为它是可憎的。算我在后一组。
3) No Alternative:To resolve names in dependant types. This comes up when using templates, as in this example:
3) No Alternative:解析依赖类型中的名称。使用模板时会出现这种情况,如下例所示:
#include <iostream>
template <typename Val>
class ValHolder
{
private:
Val mVal;
public:
ValHolder (const Val& val)
:
mVal (val)
{
}
Val& GetVal() { return mVal; }
};
template <typename Val>
class ValProcessor
:
public ValHolder <Val>
{
public:
ValProcessor (const Val& val)
:
ValHolder <Val> (val)
{
}
Val ComputeValue()
{
// int ret = 2 * GetVal(); // ERROR: No member 'GetVal'
int ret = 4 * this->GetVal(); // OK -- this tells compiler to examine dependant type (ValHolder)
return ret;
}
};
int main()
{
ValProcessor <int> proc (42);
const int val = proc.ComputeValue();
std::cout << val << "\n";
}
4) Alternatives Available:As a part of coding style, to document which variables are member variables as opposed to local variables. I prefer a different naming scheme where member varibales can never have the same name as locals. Currently I'm using mName
for members and name
for locals.
4)可用的替代方案:作为编码风格的一部分,记录哪些变量是成员变量而不是局部变量。我更喜欢不同的命名方案,其中成员变量永远不能与本地人同名。目前我正在mName
为会员和name
当地人使用。
回答by rlbond
One other case is when invoking operators. E.g. instead of
另一种情况是调用运算符时。例如代替
bool Type::operator!=(const Type& rhs)
{
return !operator==(rhs);
}
you can say
你可以说
bool Type::operator!=(const Type& rhs)
{
return !(*this == rhs);
}
Which might be more readable. Another example is the copy-and-swap:
这可能更具可读性。另一个例子是复制和交换:
Type& Type::operator=(const Type& rhs)
{
Type temp(rhs);
temp.swap(*this);
}
I don't know why it's not written swap(temp)
but this seems to be common.
我不知道为什么没有写,swap(temp)
但这似乎很常见。
回答by Macke
The other uses for this (as I thought when I read the summary and half the question... .), disregarding (bad) naming disambiguation in other answers, are if you want to cast the current object, bind it in a function object or use it with a pointer-to-member.
对此的其他用途(正如我在阅读摘要和一半问题时所想的那样......),忽略其他答案中的(坏)命名消歧,是如果你想转换当前对象,将它绑定到一个函数对象中或者将它与指向成员的指针一起使用。
Casts
演员表
void Foo::bar() {
misc_nonconst_stuff();
const Foo* const_this = this;
const_this->bar(); // calls const version
dynamic_cast<Bar*>(this)->bar(); // calls specific virtual function in case of multi-inheritance
}
void Foo::bar() const {}
Binding
捆绑
void Foo::baz() {
for_each(m_stuff.begin(), m_stuff.end(), bind(&Foo:framboozle, this, _1));
for_each(m_stuff.begin(), m_stuff.end(), [this](StuffUnit& s) { framboozle(s); });
}
void Foo::framboozle(StuffUnit& su) {}
std::vector<StuffUnit> m_stuff;
ptr-to-member
ptr 到成员
void Foo::boz() {
bez(&Foo::bar);
bez(&Foo::baz);
}
void Foo::bez(void (Foo::*func_ptr)()) {
for (int i=0; i<3; ++i) {
(this->*func_ptr)();
}
}
Hope it helps to show other uses of this than just this->member.
希望它有助于展示它的其他用途,而不仅仅是 this->member。
回答by Joe Schneider
You only have to use this-> if you have a symbol with the same name in two potential namespaces. Take for example:
如果您在两个潜在的命名空间中有一个同名的符号,您只需使用 this-> 。举个例子:
class A {
public:
void setMyVar(int);
void doStuff();
private:
int myVar;
}
void A::setMyVar(int myVar)
{
this->myVar = myVar; // <- Interesting point in the code
}
void A::doStuff()
{
int myVar = ::calculateSomething();
this->myVar = myVar; // <- Interesting point in the code
}
At the interesting points in the code, referring to myVar will refer to the local (parameter or variable) myVar. In order to access the class member also called myVar, you need to explicitly use "this->".
在代码中有趣的地方,引用 myVar 将引用本地(参数或变量)myVar。为了访问也称为 myVar 的类成员,您需要显式使用“this->”。
回答by Trevor
The main (or I can say, the only) purpose of this
pointer is that it points to the object used to invoke a member function.
this
指针的主要(或者我可以说,唯一的)目的是它指向用于调用成员函数的对象。
Base on this purpose, we can have some cases that only using this
pointer can solve the problem.
基于这个目的,我们可以有一些情况,只有使用this
指针才能解决问题。
For example, we have to return the invoking object in a member function with argument is an same class object:
例如,我们必须在参数是同一个类对象的成员函数中返回调用对象:
class human {
...
human & human::compare(human & h){
if (condition)
return h; // argument object
else
return *this; // invoking object
}
};