数组操作符的重载(二十八)

我们在学习了 string 类对象后,就不禁头脑中冒出了一个问题:string 类对象还具备 C 方式字符串的灵活性吗?还能直接访问单个字符吗?那么 string 类最大限度的考虑了 C 字符串的兼容性,可以按照使用 C 字符串的方式使用 string 对象。

下来我们用 C 方式使用 string 类,看看示例代码

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string s = "a1b2c3d4e";
    int n = 0;
    
    for(int i=0; i<s.length(); i++)
    {
        if( isdigit(s[i]) )
        {
            n++;
        }
    }
    
    cout << n << endl;
    
    return 0;
}

我们这个程序是用来统计字符串中的数字的个数的,看看编译结果

再用 BCC 编译试试

同样也是 4,再来用 VS 编译器试试

VS 同样也是 4,证明这就不是偶然了。那么问题来了哈,类的对象怎么支持数组的下标访问呢?这时我们就得需要重载数组访问操作符了。数组访问符是 C/C++ 中的内置操作符,数组访问符的原生意义是数组访问和指针运算。

下来我们就复习下之前在 C 语言中学习的指针和数组

#include <iostream>
#include <string>

using namespace std;

int main()
{
    int a[5] = {0};
    
    for(int i=0; i<5; i++)
    {
        a[i] = i;
    }
    
    for(int i=0; i<5; i++)
    {
        cout << *(a + i) << endl;    // cout << a[i] << endl;
    }
    
    cout << endl;
    
    for(int i=0; i<5; i++)
    {
        i[a] = i + 10;
    }
    
    for(int i=0; i<5; i++)
    {
        cout << *(i + a) << endl;    // cout << a[i] << endl;
    }
    
    return 0;
}

我们看看编译结果

已经实现了数组的访问。那么下来说说关于数组访问操作符([])的几个知识点:a> 只能通过类的成员函数重载;b> 重载函数能且仅能使用一个参数;c> 可以定义不同参数的多个重载函数。

下来我们通过实例代码来看看重载数组访问操作符是怎样实现的

#include <iostream>
#include <string>

using namespace std;

class Test
{
    int a[5];
public:
    int& operator [] (int i)
    {
        return a[i];
    }
    
    int& operator [] (const string& s)
    {
        if( s == "1st" )
        {
            return a[0];
        }
        else if( s == "2nd" )
        {
            return a[1];
        }
        else if( s == "3rd" )
        {
            return a[2];
        }
        else if( s == "4th" )
        {
            return a[3];
        }
        else if( s == "5th" )
        {
            return a[4];
        }
        
        return a[0];
    }
    
    int length()
    {
        return 5;
    }
};

int main()
{
    Test t;
    
    for(int i=0; i<t.length(); i++)
    {
        t[i] = i;
    }
    
    for(int i=0; i<t.length(); i++)
    {
        cout << t[i] << endl;
    }
    
    cout << endl;
    
    cout << t["5th"] << endl;
    cout << t["4th"] << endl;
    cout << t["3rd"] << endl;
    cout << t["2nd"] << endl;
    cout << t["1st"] << endl;
    
    return 0;
}

我们通过重载数组操作符,可以在 C++ 中对类对象也可以使用数组那样的方式进行访问。我们还可以直接通过 t["1st"] 这种方式对数组进行访问。看看编译结果

下来我们利用数组操作符的重载来完善下我们之前实现的数组类

IntArry.h 源码

#ifndef _INTARRAY_H_
#define _INTARRAY_H_

class IntArray
{
private:
    int m_length;
    int* m_pointer;
    
    IntArray(int len);
    bool construct();
public:
    static IntArray* NewInstance(int length);
    int length();
    bool get(int index, int& value);
    bool set(int index, int value);
    int& operator [] (int index);
    IntArray& self();
    ~IntArray();
};

#endif

IntArray.cpp 源码

#include "IntArray.h"

IntArray::IntArray(int len)
{
    m_length = len;
}

bool IntArray::construct()
{
    bool ret = true;
    
    m_pointer = new int[m_length];
    
    if( m_pointer )
    {
        for(int i=0; i<m_length; i++)
        {
            m_pointer[i] = 0;
        }
    }
    else
    {
        ret = false;
    }
    
    return ret;
}

IntArray* IntArray::NewInstance(int length)
{
    IntArray* ret = new IntArray(length);
    
    if( !(ret && ret->construct()) )
    {
        delete ret;
        
        ret = 0;
    }
    
    return ret;
}

int IntArray::length()
{
    return m_length;
}

bool IntArray::get(int index, int& value)
{
    bool ret = (0 <= index) && (index <= length());
    
    if( ret )
    {
        value = m_pointer[index];
    }
    
    return ret;
}

bool IntArray::set(int index, int value)
{
    bool ret = (0 <= index) && (index <= length());
    
    if( ret )
    {
        m_pointer[index] = value;
    }
    
    return ret;
}

int& IntArray::operator [] (int index)
{
    return m_pointer[index];
}

IntArray& IntArray::self()
{
    return *this;
}

IntArray::~IntArray()
{
    delete[] m_pointer;
}

test.cpp 源码

#include <iostream>
#include <string>
#include "IntArray.h"

using namespace std;

int main()
{
    IntArray* a = IntArray::NewInstance(5);    
    
    if( a != NULL )
    {
        IntArray& array = a->self();
        
        cout << "array.length() = " << array.length() << endl;
    
        array[0] = 1;
        
        for(int i=0; i<array.length(); i++)
        {  
            cout << array[i] << endl;
        }
    }
    
    delete a;
    
    return 0;
}

我们在 IntArray.h 头文件中添加了两个函数,一个是数组操作符的重载,另一个则是返回类的引用。返回类的引用则是方便我们在 test.cpp 中可以直接以数组的方式来进行访问,看看编译结果

通过对数组操作符重载的学习,总结如下:1、string 类最大程度的兼容了 C 字符串的用法;2、数组访问符的重载能够使得对象模拟数组的行为;3、只能通过类的成员函数重载数组访问符;4、重载函数能且仅能使用一个参数。

欢迎大家一起来学习 C++ 语言,可以加我QQ:243343083。

原文地址:http://blog.51cto.com/12810168/2119201

时间: 2024-08-28 15:02:48

数组操作符的重载(二十八)的相关文章

每日算法之二十八:Longest Valid Parentheses

Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring. For "(()", the longest valid parentheses substring is "()", which has length = 2. Another example is &

angular学习笔记(二十八)-$http(6)-使用ngResource模块构建RESTful架构

ngResource模块是angular专门为RESTful架构而设计的一个模块,它提供了'$resource'模块,$resource模块是基于$http的一个封装.下面来看看它的详细用法 1.引入angular-resource.min.js文件 2.在模块中依赖ngResourece,在服务中注入$resource var HttpREST = angular.module('HttpREST',['ngResource']); HttpREST.factory('cardResource

winform学习日志(二十八)----------将汉字转化为拼音,正则表达式和得到汉字的Unicode编码

一:上图,不清楚的看代码注解,很详细了 二:具体代码 窗体代码 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Text.RegularExpressio

QT开发(二十八)——QT常用类(二)

QT开发(二十八)--QT常用类(二) 一.QDir 1.QDir简介 QDir提供对目录结构及其内容的访问. QDir通过相对或绝对路径指向一个文件. 2.QDir成员函数 QDir主要成员函数如下: QDir::QDir ( const QDir & dir ) QDir::QDir ( const QString & path = QString() ) Dir::QDir ( const QString & path, const QString & nameFil

angular学习笔记(二十八-附1)-$resource中的资源的方法

通过$resource获取到的资源,或者是通过$resource实例化的资源,资源本身就拥有了一些方法,比如$save,可以直接调用来保存该资源: 比如有一个$resource创建的服务: var service = angular.module('myRecipe.service',['ngResource']); service.factory('Recipe',['$resource',function($resource){ return $resource('/recipe/:id',

纯干货!二十八道BATJ大厂Java岗之"多线程与并发"面试题分享

年底了,又到了跳槽季啦,该刷题走起了.这里总结了一些被问到可能会懵逼的面试真题,有需要的可以看下- 一.进程与线程 进程是资源分配的最小单位,线程是cpu调度的最小单位.线程也被称为轻量级进程. 所有与进程相关的资源,都被记录在PCB中 进程是抢占处理及的调度单位:线程属于某个进程,共享其资源 一个 Java 程序的运行是 main 线程和多个其他线程同时运行. 二.Thread中的start和run方法的区别 调用start()方法会创建一个新的子线程并启动 run()方法只是Thread的一

【Unity 3D】学习笔记二十八:unity工具类

unity为开发者提供了很多方便开发的工具,他们都是由系统封装的一些功能和方法.比如说:实现时间的time类,获取随机数的Random.Range( )方法等等. 时间类 time类,主要用来获取当前的系统时间. using UnityEngine; using System.Collections; public class Script_04_13 : MonoBehaviour { void OnGUI() { GUILayout.Label("当前游戏时间:" + Time.t

企业搜索引擎开发之连接器connector(二十八)

通常一个SnapshotRepository仓库对象对应一个DocumentSnapshotRepositoryMonitor监视器对象,同时也对应一个快照存储器对象,它们的关联是通过监视器管理对象DocumentSnapshotRepositoryMonitorManagerImpl实现的 DocumentSnapshotRepositoryMonitorManagerImpl类要实现那些行为,先查看其实现接口DocumentSnapshotRepositoryMonitorManager定义

Welcome to Swift (苹果官方Swift文档初译与注解二十八)---199~208页(第四章-- 流程控制)

Value Bindings (绑定值) 在switch的case中可以绑定一个或者多个值给case体中的临时常量或者变量,这个成为绑定值. 代码样例: let anotherPoint = (2, 0) switch anotherPoint { case (let x, 0):   println("on the x-axis with an x value of \(x)") case (0, let y):   println("on the y-axis with