c++,高级20_cpp primer重载下标操作符代码示范
#define _CRT_SECURE_NO_WARNINGS
#include //下标操作,显示单个字符
#include
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); //const下标重载-不可变
void print();
private:
char *ptrChars;
static String errorMessage;
};
void String::print()
{
cout = std::strlen(ptrChars))
throw errorMessage;
return ptrChars[index];
}
String::String(char const *chars)//常量字符串,不能修改
{
chars = chars ? chars : "";
ptrChars = new char[std::strlen(chars)+1];
std::strcpy(ptrChars,chars);
}
int main()
{
String s("Hello");
//cout
关注
打赏