【发布时间】:2012-07-18 08:33:30
【问题描述】:
我有一个更新外部引用的基类,我想构建一个继承类,将这个引用作为成员嵌入。引用的一种默认初始化。
我想出了以下解决方案:
#include<iostream>
class Statefull
{
public:
Statefull( int& ref ) : _base_ref(ref) {}
int& _base_ref;
// update the extern variable
void work() { std::cout << ++_base_ref << std::endl; }
};
class Stateless : public Statefull
{
public:
// use a temporary allocation
Stateless( int* p = new int() ) :
// we cannot initialize local members before base class:
// _dummy(), Statefull(_dummy)
// thus, initialize the base class on a ref to the temporary variable
Statefull(*p),
_tmp(p),
_dummy()
{
// redirect the ref toward the local member
this->_base_ref = _dummy;
}
int* _tmp;
int _dummy;
// do not forget to delete the temporary
~Stateless() { delete _tmp; }
};
int main()
{
int i = 0;
Statefull full(i);
full.work();
Stateless less;
less.work();
}
但是在构造函数的默认参数中需要临时分配似乎很丑陋。有没有更优雅的方法来实现这种默认初始化,同时在基类构造函数中保留引用?
【问题讨论】:
-
您没有重定向引用。您刚刚为 _base_ref 引用的变量分配了一个来自 dummy 的值。您不能重定向引用,只能初始化它们。
-
继承层次有意义吗?我希望
Stateless成为基类,或者第三类作为公共基类。 -
@SimonRichter 问题是
_ref_base的声明,在Stateless中它不应该是引用,在Statefull中,它是。如果我不想重新实现work,则需要在基类中将_ref_base声明为模板,我希望避免这样做。
标签: c++ inheritance reference constructor initialization