作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我有一个通用的 IDetachable 接口(interface),它提供了一个方法:
template<class T>
class IDetachable {
public:
virtual T detached() const = 0;
};
我有这些示例类:
class A: public IDetachable<A> {
virtual A detached() const override {
// some implementation which returns a detached A object
}
};
继承B时出现的问题:
class B: public A, public IDetachable<B> {
virtual B detached() const override {
// some implementation which returns a detached B object
}
};
clang++ 告诉我:
error: virtual function 'detached' has a different return type ('B')
than the function it overrides (which has return type 'A')
在我看来,编译器会自动为 override 关键字选择第一个父级。有没有机会告诉编译器我打算用 override 关键字继承哪个父方法?
最佳答案
问题不在于如何重写其中一个,而在于您不能拥有两个具有相同签名和不同返回类型的函数。
考虑:
template<class T, class U>
class IDetachable {
public:
virtual ~IDetachable() {}
virtual T detached() const = 0;
virtual U detached() const = 0; // whoopse problem
};
无论您如何最终得到两个返回不同类型的相同签名函数,这始终是非法的。
@AdrianMay 提供了一个可行的答案。他更改了函数的签名。
关于c++ - 如何在 C++ 中使用 override 关键字进行多重泛型继承?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26230012/
我是一名优秀的程序员,十分优秀!