【C++】34 数组操作符的重载

【C++】34 数组操作符的重载_第1张图片

字符串类的兼容性

string类最大限度的考虑了C字符串的兼容性

可以按照使用C字符串的方式使用string对象

#include 
using namespace std;
int main()

{
     string s = "a1b2c3d4";
     int n = 0;
     for(int i = 0;i

输出:

4

重载数组访问操作符

数组访问符是C/C++中的内置操作符

数组访问符的原生意义是数组访问和指针运算

例:

#include 
#include 
using namespace std;
int main()
{
    int a[5];
    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; //a[i] = i+10;
    }
    for(int i=0;i<5;i++)
    {
        cout<<*(i+a)<

输出:

0
1
2
3
4

10
11
12
13
14

重载数组访问操作符

数组访问操作符([])

只能通过类的成员函数重载

重载函数能且仅能使用一个参数

可以定义不同参数的多个重载函数

例:

#include 

#include 



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 == "3td")
   {
     return a[2];
   }
     else if(s == "4td")
   {
     return a[3];
   }
     else if(s == "5td")
   {
     return a[4];
   }
   
   return a[0];
 }
  int length()
  {
    return 5;
  }
};

int main()

{
    Test t;
    for(int i=0;i

输出:

0
1
2
3
4
0
1
2
3
4

小结:

string类最大程度的兼容了C字符串的用法

数组访问符的重载能够使得对象模拟数组的行为

只能通过类的成员函数重载数组访问符

重载函数能且仅能使用一个参数

你可能感兴趣的:(c++)