我不确定自己是否会进入正确的赛道。我需要在另一个类中初始化一个参数化对象,但我不知道如何做到这一点。为了明确我的观点,代码片段是
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.Can任何人请帮助我。
答案 0 :(得分:1)
您可以使用member initialize list使用指定的构造函数初始化非静态成员变量,就像您在基类子对象的类derived
的构造函数中所做的那样。
class test
{
public:
test(int data ) : d(data)
~~~~~~~~~
{
cout<<"test: parameter's constructor "<<endl;
}
derived return_data()
{
return d;
}
private:
derived d;
};