[英]C++ Operator return difference
Can anybody explain the difference (if there is any) between the 2 versions of this [] operator?任何人都可以解释这个 [] 运算符的两个版本之间的区别(如果有的话)? Both version are working fine ...两个版本都运行良好...
class Test {
int arr[100];
int operator[](int i) {
return arr[i];
}
int & operator[](int i) {
return arr[i];
}
};
Test a;
a.arr[5] = 10;
// works for both versions:
int n = a[5];
First, you must make your operators accessible:首先,您必须使您的操作员可访问:
class Test {
private:
int arr[100];
public:
int operator[](int i) {
return arr[i];
}
int& operator[](int i) {
return arr[i];
}
};
Now, this won't compile (since arr
is private):现在,这不会编译(因为arr
是私有的):
Test a;
a.arr[5] = 10;
int operator[](int i)
returns by value (an rvalue
), making a[5] = 10;
int operator[](int i)
按值返回( rvalue
),使a[5] = 10;
impossible.不可能的。
int& operator[](int i)
returns a reference to the int
stored in arr
(an lvalue
) which makes a[5] = 10;
int& operator[](int i)
返回对存储在arr
( lvalue
)中的int
的引用,这使得a[5] = 10;
possible.可能的。
But it won't compile since your operators only differ on the return types ( int
vs. int&
).但它不会编译,因为您的运算符仅在返回类型( int
与int&
)上有所不同。 Making the one returning by value const
solves that issue:使一个按值返回const
解决了这个问题:
#include <iostream>
class Test {
private:
int arr[100];
public:
int operator[](size_t i) const { // note the const
std::cout << "using operator[]() const\n";
return arr[i];
}
int& operator[](size_t i) {
std::cout << "using operator[]() mutable\n";
return arr[i];
}
};
void test_const(const Test& t) {
std::cout << t[5] << "\n";
}
int main() {
Test a;
a[5] = 10;
std::cout << a[5] << "\n";
test_const(a);
}
Output:输出:
using operator[]() mutable
using operator[]() mutable
10
using operator[]() const
10
First, you must make your operators accessible:首先,您必须使您的操作员可访问:
class Test {
private:
int arr[100];
public:
int operator[](int i) {
return arr[i];
} // -> Case 1
int& operator[](int i) {
return arr[i];
} // ->Case 2
};
The difference between above two operators is -上述两个运算符之间的区别是 -
Case 1 -> you can use it only as R value.情况 1 -> 您只能将其用作 R 值。
Case 2 -> you can use it as "R value" as well as "L value".情况 2 -> 您可以将其用作“R 值”和“L 值”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.