繁体   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