简体   繁体   English

另一个类中的参数化对象初始化

[英]parameterized object initialization in another class

Am not sure whether I am going in the correct track or not.我不确定我是否走在正确的轨道上。 I need to initialize a parameterized object inside another class, but am not sure how to do this.我需要在另一个类中初始化一个参数化对象,但我不确定如何执行此操作。 To make my point clear the code snippet is为了明确我的观点,代码片段是

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

My intention is to initialize the derived parameterized constructor in test constructor so that value of 100 will be populated in _value.Can anybody please help me on this.我的目的是在测试构造函数中初始化派生的参数化构造函数,以便在 _value 中填充 100 的值。任何人都可以帮我解决这个问题。

You could use member initialize list to initialize non-static member variable with specified constructor, just like what you do in class derived 's constructor for base subobject.您可以使用成员初始化列表来初始化具有指定构造函数的非静态成员变量,就像您在基子对象的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