#include <iostream>
using namespace std;
class father
{
protected:
string name;
int age;
public:
father (){cout<<"父无参构造"<<endl;}
father (string n,int a):name(n),age(a){cout<<"父有参构造"<<endl;}
~father(){cout<<"父析构"<<endl;}
father (const father &other):name(other.name),age(other.age){cout<<"父拷贝构造"<<endl;}
father &operator=(const father &other)
{
if(this!=&other)
{
this->name=other.name;
this->age=other.age;
}
return *this;
}
void show(){cout<<"name="<<name<<endl;cout<<"age="<<age<<endl;}
};
class son :public father
{
private:
int hight;
public:
son (){cout<<"子无参构造"<<endl;}
son (string s,int a,int h):father(s,a),hight(h){cout<<"子有参构造"<<endl;}
~son(){cout<<"子析构"<<endl;}
son(const son &other):father(other),hight(other.hight){cout<<"子拷贝构造"<<endl;}
son &operator=(const son &other)
{
if(this!=&other)
{
father::operator=(other);
this->hight=other.hight;
}
return *this;
}
void show()
{
father::show();
cout<<"hight="<<hight<<endl;
}
};
int main()
{
son s("ss",13,12);
s.show();
return 0;
}
#include <iostream>
#include <cstring>
using namespace std;
class myString
{
private:
char *str;
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(const myString &other):size(other.size)
{
str=new char[size+1];
strcpy(str,other.str);
}
//析构函数
~myString(){delete []str;}
//拷贝赋值函数
myString &operator=(const myString &other)
{
size=other.size;
str=new char[size];
strcpy(str,other.str);
return *this;
}
//判空函数
bool myvoid()
{
return strlen(str);
}
//size函数
int mylength()
{
return strlen(str);
}
//c_str函数
char *myc_str()
{
return str;
}
//at函数
char &myat(int i)
{
return str[i];
}
//加号运算符重载
const myString operator+(const myString &n)
{ myString s(strcat(str,n.str));
return s;
}
//加等于运算重载
myString &operator+=(const myString &n)
{
size+=n.size;
char *p=new char[size];
strcpy(p,strcat(str,n.str));
delete []str;
str=p;
return *this;
}
//关系运算符重载(>)
bool operator>(const myString &n)const
{
if(strcmp(str,n.str)>0)
return true;
return false;
}
bool operator>=(const myString &n)const
{
if(strcmp(str,n.str)>=0)
return true;
return false;
}
bool operator==(const myString &n)const
{
if(strcmp(str,n.str)==0)
return true;
return false;
}
bool operator!=(const myString &n)const
{
if(strcmp(str,n.str)!=0)
return true;
return false;
}
bool operator<(const myString &n)const
{
if(strcmp(str,n.str)<0)
return true;
return false;
}
friend ostream &operator<<(ostream &L, const myString &R);
friend istream &operator>>(istream &L, myString &R);
char &operator[](int R)//[]重载
{
return str[R];
}
};
ostream &operator<<(ostream &L,const myString &R)//<<重载
{
L<<R.str;
return L;
}
istream &operator>>(istream &L,myString &R)//>>重载
{
L>>R.str;
R.size=strlen(R.str);
return L;
}