可以消除这个基类构造函数

Possible to eliminate this base-class constructor?

本文关键字:基类 构造函数      更新时间:2023-10-16

是否有办法消除Foo中的显式构造函数调用,并以某种方式将Bar::len分配给Bar的任何子类的大小?

class Bar
{
    size_t len_;
    Bar(size_t len) : len_(len) { }
};
class Foo : public Bar
{    
    Foo() : Bar(sizeof(Foo)) { }
};

您可以使用"奇怪递归模板"来通知基类派生类的类型:

template <typename Derived>
class Bar
{
    size_t len_;
protected:
    Bar() : len_(sizeof(Derived)) {}
};
class Foo : public Bar<Foo>
{
};

虚拟继承可以做你想做的:

#include <iostream>
class Bar
{
    size_t len_;
public:
    Bar(size_t len) : len_(len) {std::cout << len << 'n';}
};
class Foo : virtual public Bar //virtual inheritance
{    
    size_t foo_bigger_than_bar;
public:
    Foo() : Bar(sizeof(Foo)) { } //Bar only called if Foo is most derived
};
class Derived2: public Foo
{    
    size_t derived2_bigger_than_foo;
public:
    Derived2() : Bar(sizeof(Derived2)), Foo() { }
    // since Foo virtually derives from Bar, we have (get) to 
    // initialize Bar ourselves.
};
int main() {
    Foo f;
    std::cout << 'n';
    Derived2 d;
}

虚基类只能由最基本的派生类初始化。例如,当创建Derived2时,Foo的构造函数将构造Bar对象,因为Derived2已经构造了它。这是钻石继承的关键,比如std::fstream
这里的演示:http://codepad.org/HUlLB4Uq