C++中的重载下标运算符[]
-
C++规定,下标运算符[]必须以成员函数的形式进行重载,该重载函数在类中的声明格式如下面两种方式:
1. 返回值类型& operator[] (参数列表); // 或者 2. const 返回值类型 & operator[] (参数列表) const; 1. 使用第一种声明方式,[]不仅可以访问元素,还可以修改元素。 2. 使用第二种声明方式,[]只能访问而不能修改元素。在实际开发中,应该同时提供以上两种形式。 3. 这样做是为了适应const对象,因为通过const对象只能调用const成员函数,如果不提供第二种形式,那么将无法访问const 对象的任何元素。
实例
Boy.h
#pragma once
#include <string>
using namespace std;
class Boy{
public:
Boy(const string name = "无名", int age = 0, int salary = 0);
//可以访问, 可以修改值
int* operator[](int index);
//只能访问, 不能修改值
//const int& operator[] (int index) const;
string description() const;
private:
string name;//姓名
int age; //年龄
int salary; //薪资
};
Boy.cpp
#include <iostream>
#include <sstream>
#include "Boy.h"
Boy::Boy(const string name, int age, int salary){
this->name = name;
this->age = age;
this->salary = salary;
}
//下标0 -> 对应age
//下标1 -> 对应salary
int& Boy::operator[](int index){
if (index == 0) {
return this->age;
} else if (index == 1) {
return this->salary;
}
}
//const int& Boy::operator[](int index) const{
// if (index == 0) {
// return this->age;
// } else if (index == 1) {
// return this->salary;
// }
//}
string Boy::description() const{
stringstream ret;
ret << "姓名:" << name
<< "\t年龄:" << age
<< "\t薪资:" << salary;
return ret.str();
}
main.cpp
#include <iostream>
#include <Windows.h>
#include "Boy.h"
using namespace std;
int main(void) {
Boy boy1("张三", 18, 10000);
cout << boy1.description() << endl;
//访问对象boy1的年龄 调用int& operator[](int index);
cout << "年龄:" << boy1[0] << endl;
//访问对象boy1的薪资 调用int& operator[](int index);
cout << "薪资:" << boy1[1] << endl;
system("pause");
return 0;
}
通过重载运算符返回的引用类型可以修改类里面的数据
如果不想让外部修改数据,那么就定义为 const 类型