c++ - 调试 C++ 代码

标签 c++ arrays pointers return operator-overloading

我无法理解以下代码 (pointer or value) 中函数返回的内容。

#include<iostream>
using namespace std;
class safearay
{
    int a[10];
public:
    int& operator [](int n)
    {
        if(n<0 || n>5 )
        {
            cout<<"Exceeded bounds"<<endl;
        }
        return a[n];
    }
};
int main()
{
    safearay sa1;
    for (int j=0;j<10;j++)
    {
        sa1[j]=j*j;
    }
    for (int j=0;j<10;j++)
    {
        int u=sa1[j];
        cout<<u<<endl;
    }
}

请解释

最佳答案

int& operator [](int n)  

返回对 int 的引用。
本质上,您可以将它用作 int,但更改也会影响类中的 a[n](因为它已返回)。它就像一个没有所有 * 的指针,只是您不能更改它指向的地址。

关于c++ - 调试 C++ 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33314842/

相关文章:

c++ - 我可以使用 nullptr 作为 Linux 系统调用参数吗?

c++ - 为什么参数包扩展如此有限?

c++ - griddb编译问题

javascript - 单击按钮后如何将数据从数组插入到数组

python - 在 Python 中循环遍历多波段栅格中的每个像素

c++ - 将数据文件包含到 C++ 项目中

c - *str 和 *str++

c - 将变量的引用分配给指针会导致意外行为

c - 定义一个结构,其中一个成员指向另一个成员

c - C 中带有通过 FIFO 管道的指针的结构