开发者

C++ equivalent to Java this

开发者 https://www.devze.com 2023-03-24 17:24 出处:网络
In Java you can refer to the current object by doing: this.x = x. How do you do this in C++? Assume that each of these code examples are part of a class called Shape.

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

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

Java:

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

C++:

开发者_Go百科
public:
void setX(int x)
{
//?
}


Same word: this

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

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


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

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    


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

0

精彩评论

暂无评论...
验证码 换一张
取 消