c++ - 初始化另一个类对象中的对象。(在该构造函数上执行一些操作之后。)

标签 c++ constructor class-design object-initialization

我想初始化一个类成员,它也是另一个类对象。问题是,我必须使用在构造函数上执行一些操作后找出的变量来初始化该成员。让我展示示例代码。

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

有人可以帮我吗? 提前致谢!

最佳答案

您可以编写一个函数来为您进行计算并返回一个 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);
}

关于c++ - 初始化另一个类对象中的对象。(在该构造函数上执行一些操作之后。),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19345054/

相关文章:

java - 谁能解释为什么这段代码只在构造函数中起作用?

python - 在 Python 中查找类的静态属性

c++ - "*(pointer + integer)"在 C++ 中有什么作用?

c++ - 在 OS X 中以编程方式获取屏幕分辨率

C++ - 在类中调用与类同名的函数

java - 业务逻辑类中的抽象

java - builder 模式会不会做得太多?

c++ - 在不访问其定义的情况下使用头文件中的类?

c++ - thrift 中的 Union 显示 c++ 中设置的所有值

c# - 为什么我们需要静态私有(private)数组来初始化其他非静态私有(private)数组字段?