我收到错误 [ error: Expected unqualified-id before ‘&’ c++ 中的令牌]程序

发布于 2024-10-29 02:56:57 字数 843 浏览 1 评论 0原文

我收到一个不寻常的错误:

错误:“&”之前应有不合格的 id令牌

源代码:

// Overloading the c++ array subscript operator [ ]

#include<iostream>
using namespace std;

const int size=10;

class myArray
{
      int a[size];
    public:
      myArray()
      {}
      int & operator [](int);
      void print_array();   
};

int myArray & operator [](int x) // This is the line where error is as by compiler
{
          return a[x];
}

void myArray::print_array()
{
    for (int j=0; j < 10; j++)
        cout<<"array["<<j<<"] = "<<a[j]<<"\n";
}

int main()
{
    myArray instance;
    for (int i=0; i < size; i++)
     {
       instance[i] = i;
     }  
    instance.print_array();

    cout<<"\n\n";
    return 0;
}

I am getting a unusual error:

error: expected unqualified-id before ‘&’ token

Source code:

// Overloading the c++ array subscript operator [ ]

#include<iostream>
using namespace std;

const int size=10;

class myArray
{
      int a[size];
    public:
      myArray()
      {}
      int & operator [](int);
      void print_array();   
};

int myArray & operator [](int x) // This is the line where error is as by compiler
{
          return a[x];
}

void myArray::print_array()
{
    for (int j=0; j < 10; j++)
        cout<<"array["<<j<<"] = "<<a[j]<<"\n";
}

int main()
{
    myArray instance;
    for (int i=0; i < size; i++)
     {
       instance[i] = i;
     }  
    instance.print_array();

    cout<<"\n\n";
    return 0;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

趴在窗边数星星i 2024-11-05 02:56:57

您需要告诉编译器您的运算符 [] 函数是 myArray 的成员:

int & myArray::operator [](const int x) 
{
          return a[x];
}

有关详细信息,此页面 有不错的示例。

You need to tell the compiler that your operator [] function is a member of myArray:

int & myArray::operator [](const int x) 
{
          return a[x];
}

For more info, this page has decent examples.

青衫儰鉨ミ守葔 2024-11-05 02:56:57

问题在于您对运算符 [] 的定义

int myArray & operator [](int x) // This is the line where error is as by compiler
{
          return a[x];
}

应该是:

int & myArray::operator [](const int x) 
{
          return a[x];
}

另外,建议 [] 通常被重载,以避免跨越数组边界。因此,您的 [] 重载理想情况下应该在取消引用该索引处的数组之前检查 xsize 。如果没有这样的检查,重载 [] 的整个目的就会失败。

The problem is with your definition of the operator []

int myArray & operator [](int x) // This is the line where error is as by compiler
{
          return a[x];
}

Should be:

int & myArray::operator [](const int x) 
{
          return a[x];
}

Also, as an suggestion [] is usually overloaded so as to avoid crossing the array bounds. So your [] overloading should ideally check x against size before dereferencing the array at that index. Without such an checking the whole purpose of overloading the [] is defeated.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文