有没有办法消除Foo中的显式构造函数调用,并以某种方式将Bar :: len分配给Bar的任何子类的大小?
class Bar
{
size_t len_;
Bar(size_t len) : len_(len) { }
};
class Foo : public Bar
{
Foo() : Bar(sizeof(Foo)) { }
};
答案 0 :(得分:6)
您可以使用“奇怪的递归模板”来通知基类派生类的类型:
template <typename Derived>
class Bar
{
size_t len_;
protected:
Bar() : len_(sizeof(Derived)) {}
};
class Foo : public Bar<Foo>
{
};
答案 1 :(得分:1)
虚拟继承可能会做你想要的:
#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