C 语言提供了丰富的操作符,有:算术操作符,移位操作符,位操作符,赋值操作符,单目操作符,关系操作符,逻辑操作符,条件操作符等。接下了让我们探究一下数组操作符的重载
一、字符串类的兼容性
问题:string 类对象还具备 C 方式字符串的灵活性吗?还能直接访问单个字符吗?
- string 类最大限度的考虑了 C 字符串的兼容性
- 可以按照使用 C 字符串的方式使用 string 对象
下面看一个用 C 方式使用 string 类的示例:
#include#include using namespace std; int main() { string s = "a1b2c3d4e"; int n = 0; for (int i = 0; i
输出结果如下:
二、重载数组访问操作符
问题:类的对象怎么支持数组的下标访问?
被忽略的事实
- 数组访问符是 C/C++ 中的内置操作符
- 数组访问符的原生意义是数组访问和指针运算
下面进行指针与数组的复习:
#include#include 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; //cout << a[i] <
输出结果如下:
数组访问操作符([ ])
- 只能通过类的成员函数重载重载
- 函数能且仅能使用一个参数
- 可以定义不同参数的多个重载函数
#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 == "3rd") { return a[2]; } else if (s == "4th") { return a[3]; } else if (s == "5th") { return a[4]; } } int length() { return 5; } }; int main() { Test t; for (int i = 0; i
输出结果如下:
这个示例说明可以将字符串作为下标访问数组。
所以之前写的数组类的代码可以进一步完善啦:
IntArray.h:
#ifndef _INTARRAY_H_ #define _INTARRAY_H_ class IntArray { private: int m_length; int* m_pointer; IntArray(int len); IntArray(const IntArray& obj); 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; iconstruct()) ) { delete ret; ret = 0; } return ret; } int IntArray::length() { return m_length; } bool IntArray::get(int index, int& value) { bool ret = (0 <= index) && (index
main.cpp:
#include#include #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
输出结果如下:
三、小结
- string 类最大程度的兼容了 C 字符串的用法
- 数组访问符的重载能够使得对象模拟数组的行为
- 只能通过类的成员函数重载数组访问符
- 重载函数能且仅能使用一个参数
到此这篇关于C++超详细讲解数组操作符的重载的文章就介绍到这了,更多相关C++数组操作符重载内容请搜索0133技术站以前的文章或继续浏览下面的相关文章希望大家以后多多支持0133技术站!
以上就是C++超详细讲解数组操作符的重载的详细内容,更多请关注0133技术站其它相关文章!