gpt4 book ai didi

c++ - 从 C++ 中继承的虚拟模板类返回内部类

转载 作者:太空宇宙 更新时间:2023-11-04 11:53:30 26 4
gpt4 key购买 nike

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> >]'

最佳答案

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

Derived类中的m方法需要返回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);
}

关于c++ - 从 C++ 中继承的虚拟模板类返回内部类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17085015/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com