我想初始化一个类成员,它也是另一个类对象。问题是,我必须用我在构造函数上做一些操作后想出的变量初始化成员。让我展示一下示例代码。
class Child_class
{
private:
int var1, var2, var3;
public:
DateTime(int var1 = 1970, int var2 = 1, int var3 = 1);
};
第二课:
class Owner_class
{
private:
Child_class foo;
public:
// I have to make some string split operations on string_var variable
// and get some new variables.After that, I need to initialize child_class with new variables
Owner_class( string string_var, int test);
}
这样做的一种方法,我知道我可以写:
Owner_class::Owner_class():
Child_class(new_var1,new_var2,new_var3) {
// but since I'll find new_var1,new_var2 and new_var3 here.I couldnt use this method.
// Am I right ?
}
有人帮我吗? 提前致谢!
答案 0 :(得分:1)
您可以编写一个函数来为您进行计算并返回一个Child_class
对象,并使用它来初始化Owner_class
构造函数初始化列表中的实例:
Child_class make_child_object(string string_var, int test)
{
// do stuff, instantiate Child_class object, return it
}
然后
Owner_class(string s, int n) : foo(make_child_object(s, n) {}
如果此方法不合适,那么另一种方法是给Child_class
一个默认构造函数,并在Owner_class
构造函数体中为其赋值:
Owner_class(string s, int n)
{
// foo has been default constructed by the time you gethere.
// Do your stuff to calculate arguments of Child_class constructor.
....
// construct a Child_class instance and assign it to foo
foo = Child_class(a, b, c);
}