简体   繁体   English

'this'是python中'self'的cpp等价物吗?

[英]Is 'this' the cpp equivalent of 'self' in python?

I'm experienced in Python and now learning cpp to speed up code.我在 Python 方面很有经验,现在正在学习 cpp 来加速代码。 After reading a bit this seems to be the cpp equivalent of self .读了一点之后, this似乎是self的 cpp 等价物。 I found a question explaining the difference from a cpp user's point of view but I'd like to know any differences for a python user's point of view.我发现了一个问题,从 cpp 用户的角度解释了差异,但我想知道 python 用户的观点有什么不同。

The major difference is that you mostly don't need this in C++, because there is a syntactic distinction between defining a member and referring to it.主要区别在于您在 C++ 中通常不需要this ,因为定义成员和引用成员之间存在语法区别。

Contrast对比

Python: Python:

class Foo:
    def __init__(self):
        self._bar = 42

    def baz(self):
        return self._bar += 1

C++: C++:

class Foo {
    int bar = 42;
public:
    int baz() { return bar += 1; }
}

In addition to the answer already given, self in Python is just a conventional name chosen for the first argument of a class method which refers to the object itself that the method is called on directly.除了已经给出的答案之外,Python 中的self只是为类方法的第一个参数选择的常规名称,该名称指的是直接调用该方法的对象本身。

In C++, this is a keyword that is not explicitly specified as a parameter of a non-static class member function, but automatically refers to the instance that such a function is called on as pointer .在 C++ 中, this是一个关键字,没有明确指定为非静态类成员函数的参数,但会自动将调用此类函数的实例作为指针引用。

That means this is not a reference to the object, but a pointer to it.这意味着this不是对对象的引用,而是指向它的指针。 So所以

this.member = 4;

is not possible.不可能。 this must be dereferenced first to obtain a reference to the object from the pointer:必须首先取消引用this才能从指针获取对对象的引用:

this->member = 4;

or (uncommonly)或(不常见)

(*this).member = 4;

With a few exceptions relating to name lookup in templates, the names of members refer to the current instances member automatically, as explained in the other answer, so this-> can be dropped, usually:除了一些与模板中的名称查找相关的例外,成员的名称自动引用当前实例成员,如另一个答案中所述,因此可以删除this-> ,通常:

member = 4;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM