簡體   English   中英

另一個類中的參數化對象初始化

[英]parameterized object initialization in another class

我不確定我是否走在正確的軌道上。 我需要在另一個類中初始化一個參數化對象,但我不確定如何執行此操作。 為了明確我的觀點,代碼片段是

class base
{
private:
   bool data_present;
    public:
    /*base()
    {
    cout<<" base :default constructor called"<<endl;
    data_present = false;
    }*/
    base(bool present )
    {
    data_present = present;
    }

    bool present()
    {
    return data_present;
    }
};

class derived :public base
{
    private:
    int _value;
    public:
    /*derived()
    {
    cout<<" derived :default constructor called"<<endl;

    }*/
    derived(int value):base(1)
    {
    _value = value;
    }
};

class test
{
   public:
    test(int data )
    {
    cout<<"test: parameter's constructor "<<endl;
    }
    derived return_data()
     {
     return d;
    }

   private:
     derived d;
};

int main()
{
  test t(100);
  return 0;
}

我的目的是在測試構造函數中初始化派生的參數化構造函數,以便在 _value 中填充 100 的值。任何人都可以幫我解決這個問題。

您可以使用成員初始化列表來初始化具有指定構造函數的非靜態成員變量,就像您在基子對象的derived類的構造函數中所做的一樣。

class test
{
   public:
    test(int data ) : d(data)
                    ~~~~~~~~~
    {
    cout<<"test: parameter's constructor "<<endl;
    }
    derived return_data()
     {
     return d;
    }

   private:
     derived d;
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM