![](/img/trans.png)
[英]Creating an instance of a C++ class and calling methods on it in Python
[英]Class instance calling a member function: C++ Vs Python syntax
在一個簡單的Python類中
class Spam:
def __init__(self, num):
self.num = num
def printMsg(self, msg):
print (msg)
當我寫線
gotAny = Spam(2)
gotAny.printMsg("We are the knights who say ni")
在每個成員函數中,將隱式的self
參數作為實際調用該函數的實例進行傳遞,因此該方法對調用方的了解非常清楚。
現在 , 在C ++中 ,我們從未將多余的self
參數放入方法定義中,這在兩個方面困擾着我:
this
指針,但是它只會使事情變得更加神秘。 在this
指針既不是一個類成員,也不作為參數傳遞,那么,如何this
存在成員函數的定義里面開始? 實際上,對象的this
指針不屬於對象本身。 所以在sizeof(Spam)
的大小, this
是不添加到類的大小。
實際發生的情況與Python的處理方式非常相似(或者更好,恕我直言,因為它隱藏了此實現細節)。 當為對象調用非靜態成員函數時, 編譯器會將對象的地址作為該函數的隱藏參數傳遞。
所以在你的例子中
gotAny.printMsg("We are the knights who say ni");
可以這樣讀取:
// corrected version by juanchopanza
Spam::printMsg(&gotAny, "We are the knights who say ni");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.