C++基础知识 - 下标重载运算符[ ]

本文介绍了C++中如何通过成员函数重载下标运算符[],并提供了示例代码,说明了返回引用类型可以用于修改类内部数据,而const类型则禁止外部修改。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 类型
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值