您当前的位置: 首页 >  c++

txwtech

暂无认证

  • 3浏览

    0关注

    813博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

c++,高级20_cpp primer重载下标操作符代码示范

txwtech 发布时间:2019-12-19 14:10:43 ,浏览量:3

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             
关注
打赏
1665060526
查看更多评论
0.0393s