繁体   English   中英

C++:在另一个 ZA2F2ED4F8EBC2CBB4C21A29DC40AB6DZ 中初始化参数化 class 的 object

[英]C++: Initialising an object of a parameterized class inside another class

I want to write a C++ program in which an object of a parameterized class A-'a' has to be initialized inside another class B. I should not/can not initialize like 'A a(parameter list);' of class A while declaring the object variable 'a' which is outside the constructor of class B. The necessary parameters to the object 'a' are gotten through the constructor of B. How to initialize 'a' inside B's constructor with the required parameters ?

Class A{
public:
    A(string s)
    {cout<<s;}
};

class B{
private:
    A a;
public:
    B(string path){
        a(path);
    }
};

使用上面的代码,我得到了错误。 如何在 class B 中初始化 object a(路径)?

您正在寻找的功能是member initializer list 在您的示例中,它将像这样使用:

class B{
    B(string path) : a(path) {
    }
};

暂无
暂无

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

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