【问题标题】:Calling virtual methods of other classes in ctors在ctors中调用其他类的虚方法
【发布时间】:2013-08-29 18:16:48
【问题描述】:

在关于calling virtual methods in ctors and dtors 的问题中,以下一段源代码引用自 C++ 标准:

struct V {
   virtual void f();
   virtual void g();
};
struct A : virtual V {
   virtual void f();
};
struct B : virtual V {
   virtual void g();
   B(V*, A*);
};
struct D : A, B {
   virtual void f();
   virtual void g();
   D() : B((A*)this, this) { }
};
B::B(V* v, A* a) {
    f(); // calls V::f, not A::f
    g(); // calls B::g, not D::g
    v->g(); // v is base of B, the call is well-defined, calls B::g

    // *** This line ***
    a->f(); // undefined behavior, a’s type not a base of B
    // *****************
}

我的问题是:为什么在 B 的 ctor 中调用 a->f() 是未定义的行为?我们可以放心地假设,a 在传递给 B 的 ctor 之前已经分配好了,那为什么不能正常工作呢?

V * v = new V();
A * a = new A();
B * b = new B(v, a);

【问题讨论】:

    标签: c++ inheritance polymorphism virtual


    【解决方案1】:

    当您创建D 类型的对象时,a->f() 调用未定义。

    在您自己的示例中,a->f() 没问题,因为您在创建 B 实例之前创建了一个单独的 A 实例。

    【讨论】:

      猜你喜欢
      • 2017-06-25
      • 1970-01-01
      • 2012-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-04
      相关资源
      最近更新 更多