具有非默认构造函数的类,在类(C ++)中

时间:2011-07-23 05:51:40

标签: c++ class constructor

我有一个类,它在构造函数上有两个参数,一个 int 和一个 void(*)(void)所以通常当我需要调用它时我做它是这样的:

obj_child (int_value, pointer_to_foo);

现在我想要的是在另一个类中用常量参数实例化 obj_child

所以我试过了:

class obj_parent
{

    private:

        obj_child child_instantiation (int_value, pointer_to_foo);

};

但这似乎在我声明 child_instantiation 的行上给了我两个编译器错误,所以我猜这些参数不能传递到那里,而是传递给其他地方。

请注意, child_instantiation 应该为所有 obj_parent 实例提供相同的参数,因此不应将它们作为 obj_parent 构造函数传递参数。

声明类指针,然后在堆上创建一个新的编译,但我不想这样做,我不知道它是否有效(我的调试器无法观察引用,所以它非常很难监控它的价值观。)

class obj_parent
    {

        private:

            obj_child *child_instantiation;

    };

obj_parent::
obj_parent (void)
{

    child_instantiation = new obj_child child_instantiation (int_value, pointer_to_foo);


}

谢谢!

(请不要介意语义,孩子 - 父母与继承无关,现在就想不出更好的名字)

2 个答案:

答案 0 :(得分:3)

您必须在类的构造函数中初始化对象。

obj_parent() : child_instantiation (int_value, pointer_to_foo) {}

答案 1 :(得分:1)

这是你怎么做的

// note that this class has no constructor with 0 args
class PrimaryClass {
  public:
    PrimaryClass(int arg1, void* arg2) {
      // do something here
    }
};

class SecondaryClass {
  private:
    PrimaryClass my_obj;
  public:
    // We call the constructor to my_obj here (using initialization lists)
    SecondaryClass(int arg1, void* arg2) : my_obj(arg1, arg2) {
      // other stuff here, maybe
    }
};