操作符重载= and[]
Operator overloading = and []
现在,我必须写
st[1];
st = 5;
我必须在我的代码中改变什么才能做到这一点:
st[1] = 5;
#include <iostream>
using namespace std;
class A
{
public:
A(){this->z = 0;}
void operator = (int t) { this->x[this->z] = t+10; }
int& operator [] (int t) { this->z=t; return this->x[t]; }
private:
int x[2];
int z;
};
void main()
{
A st;
st[0]=9;
cout<<st[0];
system("pause");
}
乌利希期刊指南:现在我看到9而不是19。
内置运算符=
需要左值作为其左操作数。因此,为了编译这条语句:
st[1] = 5;
您需要将operator []
的返回类型从int
更改为int&
:
int& operator [] (int t) { return this->x[t]; }
// ^^^^
您还可以提供const
重载,如果调用operator []
的对象是const
,它将返回对const
的引用:
int const& operator [] (int t) const { return this->x[t]; }
// ^^^^^^^^^^ ^^^^^
相关文章:
- 继承函数的重载解析
- 你能重载对象变量名本身返回的内容吗
- 从父命名空间重载类型
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 重载操作程序时出错>>用于类中的字符串 memebr
- 一个关于在C++中重载布尔运算符的问题
- 不同翻译单元中不可重载的非内联函数定义
- 为什么使用SFINAE而不是函数重载
- 为什么我不能在 C++ 中的特定函数重载中调用同一函数的任何其他重载?
- 将重载的成员函数传递给函数模板
- c++:可变模板和函数重载
- 重载元组索引运算符-C++
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 重载==不适用于二进制树
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- C++核心准则 C35 对于接口类"A base class destructor should be either public and virtual, or protected and nonv
- 重载运算符new[]的行为取决于析构函数
- 为什么在c++中不应重载逗号、地址、逻辑AND和逻辑OR运算符
- 操作符重载= and[]