C++编写字符串类CNString,该类有默认构造函数、类的拷贝函数、类的析构函数及运算符重载
程序员文章站
2022-08-01 19:37:10
编码实现字符串类CNString,该类有默认构造函数、类的拷贝函数、类的析构函数及运算符重载,需实现以下“=”运算符、“+”运算、“[]”运算符、“<”运算符及“>”运算符及“==”运算符 以下为各个运算符的运算效果的详细说明: a) 字符串“=”重载运算符 CNStringstr1("abc ") ......
编码实现字符串类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<iostream> #include<string.h> 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<str2"<<endl; } if (str1 >str2 ) { cout<<"str1>str2"<<endl; } if(str1==str2) { cout<<"str1==str2"<<endl; } return 0; }
实现效果图:
下一篇: 设计并编写代码自动格斗类游戏。