我想返回对 C++ 中的数组的引用。我在下面的示例中指的是
getColor2
成员函数及其覆盖。
我的基类中有一个纯虚拟成员函数
ILed
:
[[nodiscard]] virtual const uint8_t (&getColor2() const)[4] = 0
我在子类中有这个方法
HardwareLed
:
[[nodiscard]] const uint8_t (&getColor2() const)[4] override;
我希望后一个函数能够覆盖前一个函数,但是当使用gcc(例如13.2)时,我收到以下错误消息:
<source>:62:53: error: expected ';' at end of member declaration
62 | [[nodiscard]] const uint8_t (&getColor2() const)[4] override;
| ^
| ;
<source>:62:55: error: 'override' does not name a type
62 | [[nodiscard]] const uint8_t (&getColor2() const)[4] override;
|
使用相同的源代码,但使用 clang 17.0.1 或 icx 2023.2.1 不会产生这些错误,并且应用程序可以成功编译。
这是完整的示例:https://godbolt.org/z/d7j7ozKbM
我可以求助于使用指向数组的原始指针(可能使用结构体和
reinterpret_cast
指令),但对我来说这似乎不是一个好的解决方案。 getColor
(没有2
)就是这样实现的。
我也会在 GCC 中提交一个错误,但我不确定他们是否会让我(GCC bugzilla 表示,我很快就会收到邀请?)并且他们有很多已知问题,我无法确切确定是否可以这是其中之一(例如不完整类型),因为我是一个 C++ 新手。
非常感谢任何帮助!
我会使用
std::array<uint8_t, 4>
,请参阅https://godbolt.org/z/h3TjxYv3b。
有一个优点 - 可读性:
const std::array<uint8_t, 4> &getColor2() const; // is easier to read than
const uint8_t (&getColor2() const)[4];
using arr = uint8_t[4]
也可以使用:https://godbolt.org/z/Pbxhb8h3G。
std::array<uint8_t, 4> getColor2() const;