我有以下内容:
class Base
{
protected:
std::string _name;
public:
virtual ~Base(){}
const std::string &name;
Base()
: _name ("(no name)")
, name(_name)
{}
};
template <typename T>
class BaseH : public Base
{
public:
virtual ~BaseH() {}
BaseH() : Base() {}
T& operator~(){ ; return static_cast<T&>(*this);}
};
class One : public BaseH<One>
{
public:
One() : BaseH<One>() { _name = "One"; }
};
class Two
: public One
, public BaseH<Two>
{
public:
Two() : BaseH<Two>() { _name = "Two"; }
};
int main(int argc, char *argv[])
{
std::cout << Two().name << std::endl;
return 0;
}
我想Two
从One
and派生BaseH<Two>
,因为Two
它是 , 的特化One
,并且operator~
inBaseH
必须始终返回调用它的对象类型的引用。
编译错误显然是:
In constructor ‘Two::Two()’:
error: reference to ‘_name’ is ambiguous
error: candidates are: std::string Base::_name
error: std::string Base::_name
In function ‘int main(int, char**)’:
error: request for member ‘name’ is ambiguous
error: candidates are: const string& Base::name
error: const string& Base::name
在通过构造函数委托设置引用的同时,如何在 and 中创建和_name
访问name
?最干净的方法是什么?One
Two
const