#include <iostream>
#include <string.h>
using namespace std;
class myString{
private:
char *str; //记录c风格的字符串
int size; //记录字符串的实际长度
public:
//无参构造
myString():size(10){
str=new char[size];
strcpy(str,"");
}
//有参构造
myString(const char* s){
size = strlen(s);
str = new char[size+1];
strcpy(str,s);
}
//析构函数
~myString(){
cout<<"myString::析构函数"<<endl;
}
//拷贝构造
myString(const myString& other):
str(new char( *(other.str) )),
size(other.size){
cout<<"myString::拷贝构造"<<endl;
}
//拷贝赋值函数
myString& operator =(const myString& other){
if(this != &other){
this->str=other.str;
this->size=other.size;
}
cout<<"myString::拷贝赋值函数"<<endl;
return *this;
}
//判空函数
bool isempty(){
return (this->size<=0)? 0:1;
}
//size函数
int mySize(){
return this->size;
}
//c_str
char *c_str(){
return this->str;
}
//at
char& at(int pos){
if(pos>=this->size || pos<0){
return (this->str[0]);
}else{
return this->str[pos];
}
}
//成员函数版实现加号运算符重载
const myString operator+ (const myString &s)const{
myString temp;
// delete temp;
strcat(temp.str,strcat(this->str,s.str));
temp.size = this->size + s.size;
return temp;
}
};
int main()
{
myString s1("123abc");
if(!s1.isempty()){
cout<<"为空"<<endl;
}else {
cout<<"不为空"<<endl;
}
cout<<"size="<<s1.mySize()<<endl;
cout<<"c_str="<<s1.c_str()<<endl;
cout<<"at="<<s1.at(2)<<endl;
myString s2;
s2 =s1 + s1;
cout<<"s2->size="<<s2.mySize()<<endl;
return 0;
}
c++day5
猜你喜欢
转载自blog.csdn.net/sunmumu122212222/article/details/131842653
今日推荐
周排行