简体   繁体   English

c++ 相当于 python self.attribute = ObjectInstance()

[英]c++ equivalent to python self.attribute = ObjectInstance()

i want to know if there is an equivalent way of doing this in c++:我想知道在 c++ 中是否有等效的方法:

class B:
    def foo(self,parameter):
        print("B method call from A, with non static method",parameter)

class A:
    def __init__(self):
        self.b = B()

parameter = 10
a = A()
a.b.foo(parameter)

self.b in C++ could be this->b , but also just b as this is implicit in C++. self.b中的 self.b 可以是this->b ,但也可以只是b ,因为this隐含在 C++ 中。

However, in C++, you have to declare (member) variables, while in Python you create them by assigning to them and the type of the variable is determinated by this assignment and can be changed.但是,在 C++ 中,您必须声明(成员)变量,而在 Python 中,您通过分配给它们来创建它们,并且变量的类型由该分配确定并且可以更改。 So next code is similar (not compiled, tested):所以下一个代码是相似的(未编译,测试):

#include <iostream>

class B { public: void foo(int x) { std::cout << x << "\n"; } };

class A { public: B b; }

int main() { A a; a.b.foo(3); }

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

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