下表操作符
2016-03-21 21:22
447 查看
#include <iostream> using namespace std; class String { public: String(char const *chars = ""); // 构造函数 char &operator[](std::size_t index) throw(String); // 这是下标操作符重载。这个一个可变成员函数, char operator[](std::size_t index) const throw(String); // 这个是常量成员函数, void print(); private: char *ptrChars; // 私有的数据成员是一个字符指针, static String errowMessage; // 将其errowMessage定义为静态的字符串, }; void String::print() { cout << ptrChars << endl; } String String::errowMessage("SubScript out of range"); char &String::operator[](std::size_t index) throw(String) // 定义下标指针, { if (index >= std::strlen(ptrChars)) // 如果下表的数目超过总的数目抛出异常, throw errowMessage; return ptrChars[index]; // 返回到对应位置的下标字符, } char String::operator[](std::size_t index) const throw(String) // 这个是常量成员函数的定义, { if (index >= std::strlen(ptrChars)) throw errowMessage; return ptrChars[index]; } String::String(char const *chars) { chars = chars ? chars : ""; // 如果这是一个空指针就让它变成一个空字符串, ptrChars = new char[std::strlen(chars) + 1]; // 动态的创建一个字符数组,字符数组的字符串要足够的大,加1就是存放字符的最后一个\t, std::strcpy(ptrChars, chars); // 这个是copy将chars指针copy到ptrChars指针里, } int main() { String s("xiaocui"); s.print(); cout << s[0] << endl; s[0] = 'A'; s.print(); String const s2("cui"); // 这个调用const函数重载, cout << s2[1] << endl; return 0; }
相关文章推荐
- H5 - HTML5新增标签
- cygwin 安装 ffplay
- day11_分区表------子分区的母模板(10g)
- day11_分区表——分区表常用维护
- day11_分区表——11g新特性
- hdoj--1060--Leftmost Digit(数学)
- python的时间处理
- netty-mina深入学习与对比(一)
- eclipse结合axis2发布webservice踩坑记录
- CCD及CMOS尺寸计算
- spring学习笔记(10)@AspectJ研磨分析[1]入门、注解基本介绍
- 数据结构队列C++代码实现
- 使用ThreadGroup模拟线程池
- JAVA学习笔记(二)
- JAVA_String_字符串操作
- BZOJ solve 100 纪念
- iOS开发网络篇—数据安全
- Java爬虫,信息抓取的实现
- 网络框架之volley
- BZOJ solve 100 纪念