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

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

我想知道在 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 在 C++ 中可以是 this->b,但也可以只是 b,因为 this 在 C++ 中是隐含的。

然而,在 C++ 中,您必须声明(成员)变量,而在 Python 中,您通过分配给它们来创建它们,并且变量的类型由该分配确定并且可以更改。所以接下来的代码类似(未编译,测试):

#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); }