2

我有以下内容:

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;
}

我想TwoOneand派生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?最干净的方法是什么?OneTwoconst

4

1 回答 1

3

看起来你遇到了钻石问题。你试过虚拟继承吗?

例如:

template <typename T>
class BaseH : virtual public Base
{
    // ...
};

class One : virtual public BaseH<One>
{
    // ...
};

编辑:进一步阅读钻石问题:http ://www.cprogramming.com/tutorial/virtual_inheritance.html

于 2012-10-23T13:23:35.207 回答