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> >]'
答案 0 :(得分:1)
您尝试根据返回类型覆盖函数。类Base::Inner
与Derived::Inner
不同,因此您无法从派生类中覆盖基类中的m
方法。
m
类中的Derived
方法需要返回Base::Inner
。但是,这将导致object slicing,因此您无法直接执行此操作。相反,您必须返回引用或指针。
我建议使用后者,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);
}