您的位置:首页 > 其它

下表操作符

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: