gpt4 book ai didi

c++ - 在 C++ 中传递引用

转载 作者:行者123 更新时间:2023-11-28 00:42:02 25 4
gpt4 key购买 nike

我正在编写一个用于在数组上重载“[]”运算符的程序。这是我的代码

 / / A safe array example.
#include <iostream>
#include <cstdlib>
using namespace std;

class atype {
int a[3];
public:
atype(int i, int j, int k) {
a[0] = i;
a[1] = j;
a[2] = k;
}
int &operator[](int i);
};

// Provide range checking for atype.
int &atype::operator[](int i)
{
if(i<0 || i> 2) {
cout << "Boundary Error\n";
exit(1);
}
return a[i];
}

int main()
{
atype ob(1, 2, 3);

cout << ob[1]; // displays 2
cout << " ";

ob[1] = 25; // [] appears on left
cout << ob[1]; // displays 25

ob[3] = 44; // generates runtime error, 3 out-of-range

return 0;
}

在我们声明的类中

int &operator[](int i);

在类之外定义为

int &atype::operator[](int i)

应该是int atype::&operator[](int i)但它给我错误。

1>c:\users\abc\documents\visual studio 2010\projects\[]overl\[]overl\[]overl.cpp(17): error C2589: '&' : illegal token on right side of '::'
1>c:\users\abc\documents\visual studio 2010\projects\[]overl\[]overl\[]overl.cpp(17): warning C4091: '' : ignored on left of 'int' when no variable is declared
1>c:\users\abc\documents\visual studio 2010\projects\[]overl\[]overl\[]overl.cpp(17): error C2143: syntax error : missing ';' before '::'
1>c:\users\abc\documents\visual studio 2010\projects\[]overl\[]overl\[]overl.cpp(17): error C2059: syntax error : '::'
1>c:\users\abc\documents\visual studio 2010\projects\[]overl\[]overl\[]overl.cpp(18): error C2143: syntax error : missing ';' before '{'
1>c:\users\abc\documents\visual studio 2010\projects\[]overl\[]overl\[]overl.cpp(18): error C2447: '{' : missing function header (old-style formal list?)

但是当我尝试 int &atype::operator[](int i)它起作用了。有人能解释一下我们是在传递对类还是 operator[](int i) 的引用

最佳答案

一般语法是

<return type> class-name :: function-name (argument-list)

在您的情况下,返回类型是对整数的引用,即 int &

int &atype::operator[](int i) 只是语法正确

关于c++ - 在 C++ 中传递引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18426658/

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