可以消除这个基类构造函数
Possible to eliminate this base-class constructor?
是否有办法消除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
相关文章:
- C++17 使用驱动类常量作为基类构造函数的参数来初始化基类构造函数
- 派生类(构造函数具有参数)和基类(构造函数缺少参数)之间没有可行的转换
- 在成员构造函数之后调用基类构造函数
- 如何在将原始指针移动到基类构造函数之前从unique_ptr中提取原始指针
- C++:在共享对象中调用抽象基类构造函数/未定义的符号
- 如何在 C++ 中将参数传递给基类构造函数
- 将数据成员的指针传递给基类构造函数是否安全?
- 使用基类构造函数初始化儿童类
- 使用基类构造函数的子类构造函数的大纲定义
- MSVC 无法识别继承模板类的模板类的"直接"基类构造函数
- 子类的构造函数后跟冒号后的基类构造函数是什么意思?
- 是否可以使用基类构造函数通过派生类将值初始化为基类私有成员?
- 当派生类无法轻易将参数传递到基类时,如何调用基类构造函数
- 是否可以在运行时切换到不同的基类构造函数?
- 对基类构造函数的未定义引用
- 如何为基类构造函数中的每个子类执行特定任务
- 将类传递到基类构造函数的模板参数中?
- 如何在基类构造函数中使用派生类成员
- (为什么)纯虚拟派生类中是否需要虚拟基类构造函数调用?
- 使用相同的参数调用基类C++构造函数