gpt4 book ai didi

C++横向协变: return type differs due to incomplete type

转载 作者:行者123 更新时间:2023-12-03 06:51:45 26 4
gpt4 key购买 nike

我正在试验协方差并提出以下示例,该示例至少不能使用 clang 11 和 VS2015 进行编译:

class Number {
public:
virtual ~Number () = default;
virtual Number const * increment()const = 0;
};

class Even;

class Odd : public Number {
public:
// error: increment() is not covariant because Even is incomplete
Even const * increment()const;
};

class Even : public Number {
public:
Odd const * increment()const;
};
它与 Covariant return types, const-ness, and incomplete classes有关但不是重复的,因为两个被覆盖的函数的常量性是相同的。
这甚至得到标准的支持吗?
有没有办法解决这个问题或任何建议来实现类似的行为?

最佳答案

虽然可能有您想要实现的解决方法,但显示的代码无效。
根据 class.virtual#9 :

If the class type in the covariant return type of D​::​f differs from that of B​::​f, the class type in the return type of D​::​f shall be complete at the point of declaration of D​::​f or shall be the class type D. ...


链接文本中有此规则的示例。
在您的情况下,由于 Odd::increment 的返回类型不是 Number , 和 Even在声明时不完整 Odd::increment ,代码格式错误。
我在这个错误中找到了答案,因此 deleted answer由@Brian 撰写,以回答您所链接的问题。

关于C++横向协变: return type differs due to incomplete type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64753508/

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