C ++:是否可以在构造函数完成之前调用对象的函数?

时间:2010-10-14 17:30:45

标签: c++ function constructor instance

在C ++中,是否可以在该实例的构造函数完成之前调用实例的函数?

e.g。如果A的构造函数实例化B,B的构造函数调用A的函数之一。

4 个答案:

答案 0 :(得分:11)

是的,这是可能的。但是,您有责任调用的函数不会尝试访问任何没有调用其构造函数的子对象。通常这很容易出错,这就是应该避免的原因。

答案 1 :(得分:4)

这很可能

class A;
class B { 
public:
  B(A* pValue);
};

class A {
public:
  A() {
    B value(this);
  }
  void SomeMethod() {}
};

B::B(A* pValue) {
  pValue->SomeMethod();
}

答案 2 :(得分:1)

这有可能,有时甚至是必要的(虽然它会放大无意中对城市街区进行平整的能力)。例如,在C ++ 98中,不是为常见初始化定义一个人工基类,而是在C ++ 98中经常看到由每个构造函数调用的init函数完成的操作。我不是在谈论两阶段构造,这只是邪恶,而是关于分解常见的初始化。

C ++ 0x提供构造函数转发,这将有助于缓解问题。

对于实践中它是危险的,必须要特别小心什么是初始化而不是。而对于纯正式的,标准中有一些不必要的模糊措辞,可以解释为如果对象在构造函数成功完成之前并不存在。但是,由于这种解释会使UB使用,例如一个init函数来分解常见的初始化,这是一种常见的做法,它可以被忽略。

干杯&第h。,

答案 3 :(得分:-2)

你为什么要那样做?不,由于您需要将对象作为其参数之一,因此无法完成。 C ++成员函数实现和C函数是不同的东西。

c ++代码

class foo
{
    int data;
    void DoSomething()
    {
        data++;
    }
};


int main()
{
    foo a;              //an object
    a.data = 0;         //set the data member to 0
    a.DoSomething();    //the object is doing something with itself and is using 'data'
}

这是一个简单的方法C。

typedef void (*pDoSomething) ();
typedef struct __foo
{
    int data;
    pDoSomething ds;    //<--pointer to DoSomething function
}foo;

void DoSomething(foo* this)
{
    this->data++;   //<-- C++ compiler won't compile this as C++ compiler uses 'this' as one of its keywords.
}

int main()
{
    foo a;
    a.ds = DoSomething; // you have to set the function.
    a.data = 0;
    a.ds(&a);       //this is the same as C++ a.DoSomething code above.
}

最后,您的问题的答案是以下代码。

void DoSomething(foo* this);
int main()
{
    DoSomething( ?? );  //WHAT!?? We need to pass something here.
}

看,你需要一个对象传递给它。答案是否定的。