C++笔记 第三十四课 数组操作符的重载---狄泰学院

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_42187898/article/details/84066381

如果在阅读过程中发现有错误,望评论指正,希望大家一起学习,一起进步。
学习C++编译环境:Linux

第三十四课 数组操作符的重载

1.问题

string类对象还具备C方式字符串的灵活性吗?还能直接访问单个字符吗?
绝对支持数组直接访问单个字符,使用操作符重载函数进行就可以

2.字符串类的兼容性

string类最大限度的考虑了C字符串的兼容性
可以按照使用C字符串的方式使用string对象
string s = “a1b2c3d4e”;
int n = 0;
for(int i = 0; i<s.length(); i++)
{
if( isdigit(s[i]) )
{
n++;
}
}

34-1 用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;
}
运行结果:4

3.问题

类的对象怎么支持数组的下标访问?

4.重载数组访问操作符

被忽略的事实。。
数组访问符是C/C++中的内置操作符
数组访问符的原生意义是数组访问和指针运算—访问某个元素
C语言深度剖析:a[n] <–> *(a + n) <–> *(n + a) <–>n[a]

34-2 指针与数组的复习

#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;    // *(i+a)==>*(a+i) 
                          //a[i] = i + 10;
    }
    
    for(int i=0; i<5; i++)
    {
        cout << *(i + a) << endl;  // cout << a[i] << endl;
    }
    
    return 0;
}
运行结果
0
1
2
3
4
10
11
12
13

数组访问操作符([])—原生意义—注意事项
只能通过类的成员函数重载
重载函数能且仅能使用一个参数
可以定义不同参数的多个重载函数

34-3 重载数组访问操作符

#include<iostream>
#include<string>
using namespace std;
class Test
{
    int a[5];
public:
    int& operator [] (int i)//reference
    {
	return a[i];
    }
    //Operator overloading
    int& operator [] (const string& s)//reference
    {
        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.operator[](i) = i;
    }
    for (int i =0; i<t.length();i++)
    {
	cout<< t[i]<<endl;
    }
    
    cout << t["5th"] << endl;
    cout << t["4th"] << endl;
    cout << t["3rd"] << endl;
    cout << t["2nd"] << endl;
    cout << t["1st"] << endl;
    return 0;
}
运行结果
0
1
2
3
4
4
3
2
1
0

IntArray 数组类的完善
BCC编译器
小结
string类最大程度的兼容了C字符串的用法
数组访问符的重载能够使得对象模拟数组的行为
只能通过类的成员函数重载数组访问符
重载函数能且仅能使用一个参数

猜你喜欢

转载自blog.csdn.net/weixin_42187898/article/details/84066381