简体   繁体   English

调用成员函数的类实例:C ++与Python语法

[英]Class instance calling a member function: C++ Vs Python syntax

In a simple Python class 在一个简单的Python类中

class Spam:
    def __init__(self, num):
        self.num = num
def printMsg(self, msg):
    print (msg)

When I write the lines 当我写线

gotAny = Spam(2)
gotAny.printMsg("We are the knights who say ni")

in each member function an implicit self argument is passed as the instance that actually called the function, so the way the caller is known by the method is clear enough. 在每个成员函数中,将隐式的self参数作为实际调用该函数的实例进行传递,因此该方法对调用方的了解非常清楚。

In C++ now , we never put that extra self argument in method definitions, which troubles me in two ways : 现在在C ++中 ,我们从未将多余的self参数放入方法定义中,这在两个方面困扰着我:

  • How is the caller known ? 来电者如何得知?
  • There is a this pointer but it only makes things more mysterious. 有一个this指针,但是它只会使事情变得更加神秘。 The this pointer is neither a class member nor passed as an argument, so how does this exist inside member function definitions to begin with ? this指针既不是一个类成员,也不作为参数传递,那么,如何this存在成员函数的定义里面开始?

Indeed an object's this pointer is not part of the object itself. 实际上,对象的this指针不属于对象本身。 So in sizeof(Spam) , the size of this is not added to the size of the class. 所以在sizeof(Spam)的大小, this是不添加到类的大小。

What actually happens is very similar to Python's way of dealing with it (or IMHO better as it hides away this implementation details). 实际发生的情况与Python的处理方式非常相似(或者更好,恕我直言,因为它隐藏了此实现细节)。 When a nonstatic member function is called for an object, the address of the object is passed by the compiler as a hidden argument to the function. 当为对象调用非静态成员函数时, 编译器会将对象的地址作为该函数的隐藏参数传递。

So in your example 所以在你的例子中

gotAny.printMsg("We are the knights who say ni");

can be read this way: 可以这样读取:

// corrected version by juanchopanza
Spam::printMsg(&gotAny, "We are the knights who say ni"); 

Source 资源

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

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