1

Derived<T>继承自Base<T>Derived<T>::m应该返回一个Derived<T>::Inner对象。什么错误,我不明白。

考虑以下代码:

template <typename T>
class Base {
public:
    class Inner {
    public:
        virtual void x() = 0;
    };
    virtual Inner m(std::string arg) = 0;
};

template <typename U>
class Derived : Base<U> {
public:

    class Inner : Base<U>::Inner {
    public:
        virtual void x();
    };
    virtual Inner m(std::string arg);
};

template <typename U>
Derived<U>::Inner Derived<U>::m(std::string arg) {
    std::cout << "calling Derived::m() " << arg << std::endl;
    return new Inner();
}

template <typename U>
void Derived<U>::Inner::x() {
    std::cout << "calling x" << std::endl;
}

Derived<std::string>* d = new Derived<std::string>();
Derived<std::string>::Inner* inner = d->m("test");
inner->x();

我收到以下错误:

invalid covariant return type for 
   'Derived<U>::Inner Derived<U>::m(std::string) [with U = std::basic_string<char, std::char_traits<char>, std::allocator<char> >]'
overriding 'Base<T>::Inner Base<T>::m(std::string) [with T = std::basic_string<char, std::char_traits<char>, std::allocator<char> >]'
4

1 回答 1

1

您尝试根据返回类型覆盖函数。该类Base::Inner与 不同Derived::Inner,因此您不能m从派生类覆盖基类中的方法。

类中的m方法Derived需要返回Base::Inner。但是,这将导致对象切片,因此您不能直接执行此操作。相反,您必须返回引用或指针。

我建议后者,通过使用std::unique_ptr.

也许是这样的:

template<typename U>
class Base
{
public:
    class Inner { ... };

    using inner_ptr = std::unique_ptr<Base<U>::Inner>;

    virtual inner_ptr m(const std::string&) = 0;
};

template<typename U>
class Derived : public Base<U>
{
public:
    Base<U>::inner_ptr m(const std::string&);

    class LocalInner : public Base<U>::Inner { ... };
};

template<typename U>
inline Base<U>::inner_ptr m(const std::string& arg)
{
    return Base<U>::inner_ptr(new LocalInner);
}
于 2013-06-13T10:44:00.110 回答