簡體   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