摘要:本文主要向大家介绍了C/C++知识点之C++编写字符串类CNString,该类有默认构造函数、类的拷贝函数、类的析构函数及运算符重载,通过具体的内容向大家展示,希望对大家学习C/C++知识点有所帮助。
本文主要向大家介绍了C/C++知识点之C++编写字符串类CNString,该类有默认构造函数、类的拷贝函数、类的析构函数及运算符重载,通过具体的内容向大家展示,希望对大家学习C/C++知识点有所帮助。
编码实现字符串类CNString,该类有默认构造函数、类的拷贝函数、类的析构函数及运算符重载,需实现以下“=”运算符、“+”运算、“[]”运算符、“<”运算符及“>”运算符及“==”运算符
以下为各个运算符的运算效果的详细说明:
a) 字符串“=”重载运算符
CNStringstr1("abc ");
CNString str2 = str1;
b) 字符串“+”运算
CNStringstr1("abc");
CNStringstr2("efg ");
str1 = str1 + str2;
c) 字符串“[]”运算
CNString nstring1("abc");
cout<< nstring1[0] ;// 则屏幕显示a
cout<< nstring1[2] ; // 则屏幕显示c
d) “<”运算符
CNStringstr1("abc");
CNStringstr2("efg");
if (str1 <str2 ){
cout<<“str1<str2”<<endl;
}
e) “>”运算符
CNStringstr1("abc");
CNStringstr2("efg");
if (str1 >str2 ){
cout<<“str1>str2”<<endl;
}
f) “==”运算符
CNStringstr1("abc");
CNStringstr2("efg");
if (str1 == str2){
cout<<“str1==str2”<<endl;
}
代码实现:
复制代码
#include
#include
using namespace std;
class CNString
{
private:
char *str_F;
public:
CNString(){str_F=NULL;};//默认构造函数
CNString(char *str);//有参构造函数
CNString(const CNString &other);//类的拷贝函数
~CNString();//类的析构函数
CNString &operator=(const CNString &obj);//"="号重载
CNString &operator+(const CNString &obj);//"+"号重载
char& operator[](int i);//"[]"号重载
bool operator<(const CNString &obj);//"<"号重载
bool operator>(const CNString &obj);//">"号重载
bool operator==(const CNString &obj);//"=="号重载
void print()//打印str_F的结果
{
cout<<str_F<<endl;
}
};
CNString::CNString(char *str)
{
str_F = new char(strlen(str)+1);
if(str_F!=0) strcpy(str_F,str);
}
CNString::CNString(const CNString &obj)
{
str_F = new char(strlen(obj.str_F)+1);
if(str_F!=0) strcpy(str_F,obj.str_F);
}
CNString::~CNString()
{
delete []str_F;
}
CNString & CNString::operator=(const CNString &obj)
{
char * tem=new char(strlen(obj.str_F)+1);
strcpy(tem,obj.str_F);
str_F=tem;
delete[]tem;
return *this;
}
CNString & CNString::operator+(const CNString &obj)
{
strcat(str_F,obj.str_F);
return *this;
}
char &CNString::operator[](int i)
{
return str_F[i];
}
bool CNString::operator<(const CNString &obj)
{
int c = strcmp(str_F,obj.str_F);
if(c<0) return true;
else return false;
}
bool CNString::operator>(const CNString &obj)
{
int c = strcmp(str_F,obj.str_F);
if(c>0) return true;
else return false;
}
bool CNString::operator==(const CNString &obj)
{
int c = strcmp(str_F,obj.str_F);
if(c==0) return true;
else return false;
}
int main()
{
CNString str1("abc ");
CNString str2("edf");
CNString str3;
cout<<"实现运算符+和=重载后:"<<endl;
str3 = str1 + str2;
str3.print();
cout<<"实现运算符[]重载后:"<<endl;
CNString nstring1("abc");
cout<<nstring1[0]<<endl;
cout<<"实现运算符'<' '>' '=='重载后:"<<endl;
if (str1 <str2 )
{
cout<<"str1
}
if(str1==str2)
{
cout<<"str1==str2"<<endl;
}
return 0;
}
本文由职坐标整理并发布,了解更多内容,请关注职坐标编程语言C/C+频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号