gpt4 book ai didi

c++ - 如何在 C++ 中使用 override 关键字进行多重泛型继承?

转载 作者:可可西里 更新时间:2023-11-01 16:36:20 25 4
gpt4 key购买 nike

我有一个通用的 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/

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