在派生类对象构造后调用虚函数

Call virtual function after derived class object construction

本文关键字:调用 函数 派生 对象      更新时间:2023-10-16

下面是一些示例代码:

#include <iostream>
class A {
public:
    virtual void foo() {
        std::cout << "base" << std::endl;
    }
    A() {
        foo();
    }
};
class B : public A {
    int a;
public:
    void foo() {
        std::cout << "derived" << std::endl;
    }
    B(int a) :
        a(a) {}
};
int main() {
    B o(1);
    return 0;
}

我希望每次构造某个派生对象时都会调用foo() A。我不想在每个派生类构造函数中显式调用foo()

有没有办法以某种优雅的方式做到这一点?

无论您做什么,都无法从基类构造函数调用重写的foo()。 调用基类构造函数时,派生类对象尚未构造,因此无法调用其任何方法或访问其任何成员。 对于虚函数和常规函数也是如此。 在基类构造函数中,this指针指向基类,而不是派生类。

一种可能的解决方法是将构造委托给客户端必须调用的单独函数。然后在构造后让该函数调用 foo:

class A {
public:
    virtual void foo() {
        std::cout << "base" << std::endl;
    }
    template<typename T, typename ... Args>
    static T construct(Args ... args)
    {
        T newT{ args... };
        newT.foo();
        return std::move(newT);
    }
protected:
    A() {
        //Construct A
    }
};
class B : public A {
    int a;
public:
    void foo() {
        std::cout << "derived" << std::endl;
    }
    B(int a) :
        a(a) {}
};
int main()
{
    B o = A::construct<B>(1);
    A a = A::construct<A>();
    return 0;
}