java C++相当于Java this

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6905598/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 17:51:12  来源:igfitidea点击:

C++ equivalent to Java this

javac++this

提问by nobody

In Java you can refer to the current object by doing: this.x = x. How do you do this in C++?

在 Java 中,您可以通过执行以下操作来引用当前对象:this.x = x。你如何在 C++ 中做到这一点?

Assume that each of these code examples are part of a class called Shape.

假设这些代码示例中的每一个都是名为Shape.

Java:

爪哇:

public void setX(int x)
{
this.x = x;
}

C++:

C++:

public:
void setX(int x)
{
//?
}

回答by Benjamin Lindley

Same word: this

同一句话: this

Only difference is it is a pointer, so you need to use the ->operator:

唯一的区别是它是一个指针,所以你需要使用->运算符:

void setX(int x)
{
    this->x = x;
}

回答by Edwin Buck

The C++ equivalent is this, but there are a few differences.

C++ 等价物是this,但有一些区别。

This is a pointer to the object in question, not a reference; so, you must use pointer dereferencing operators before accessing fields or methods.

这是指向相关对象的指针,而不是引用;因此,您必须在访问字段或方法之前使用指针解引用运算符。

(*this).method(...)
(*this).field

or, using the more popular syntax

或者,使用更流行的语法

this->method(...)
this->field    

回答by Paul Sonier

The C++ equivalent is this; that is, the keyword is the same.

C++ 等价物是this; 也就是说,关键字是一样的。