重写返回数组常量引用的类方法

问题描述 投票:0回答:1

我有这段代码,其中 MyClass 派生自 iClass 接口,并且有一个方法返回对成员数组 arr 的常量引用:

#include <iostream>

class iMyClass
{
    public:
        virtual const int (&getDataRef())[100] = 0;
};

class MyClass : public iMyClass
{
    public:
        MyClass(): arr{}{};
        const int (&getDataRef())[100];
        void set() {arr[5] = 5;};
    private:
        int arr[100];
};

const int (&MyClass::getDataRef())[100]
{
    return arr;
}

int main()
{
    MyClass a;
    const int (&brr)[100] = a.getDataRef();
    a.set();
    std::cout << brr[5];

    return 0;
}

这符合我的预期(即打印 5)。

但是如果我在 MyClass 中的 getDataRef() 声明末尾添加 'override' 以表明基类函数被重写,编译就会失败:

    const int (&getDataRef())[100] override;

控制台输出:

main.cpp:21:34: error: expected ‘;’ at end of member declaration
   21 |     const int (&getDataRef())[100] override;
      |                                  ^
      |                                   ;
main.cpp:21:36: error: ‘override’ does not name a type
   21 |     const int (&getDataRef())[100] override;
      |                                    ^~~~~~~~

有人知道为什么吗?我可能可以使用 typedef 来定义数组,但我想了解为什么它无法编译。如果没有typdef,如何解决这个问题?

c++ arrays reference overriding
1个回答
0
投票

应该是

const int (&getDataRef() override)[100];
。但实际上,请使用
typedef
或更好的
std::array<int, 100>
来代替。这是语法上的混乱,我怀疑任何人都能轻松理解这里发生的事情。

– 伊克西萨维宁

© www.soinside.com 2019 - 2024. All rights reserved.