父子进程回顾
#include <iostream>
using namespace std;
class Father
{
public:
int *password;
Father(){cout<<"father 无参构造"<<endl;}
Father(int *p):password(p){cout<<"father 有参构造"<<endl;}
Father(const Father &other):password(new int(*(other.password)))
{
cout<<"father 拷贝构造函数"<<endl;
}
Father& operator=(const Father&other)
{
if(this!=&other)
{
this->password=new int(*(other.password));
}
cout<<"father 拷贝赋值函数"<<endl;
return *this;
}
~Father(){cout<<"father 析构函数"<<endl;}
};
class Stu:public Father
{
private:
int paper;
public:
Stu(){cout<<"stu无参构造"<<endl;}
Stu(int *pa,int p):Father(pa),paper(p){cout<<"Stu 有参构造"<<endl;}
~Stu(){cout<<"stu 析构函数"<<endl;}
Stu(const Stu &other):Father(other),paper(other.paper)
{
cout<<"Stu 拷贝构造"<<endl;
}
Stu &operator=(const Stu &other)
{
if(this!=&other)
{
Father::operator=(other);
this->paper=other.paper;
}
cout<<"Stu 拷贝赋值函数"<<endl;
return *this;
}
void show()
{
cout<<"password="<<password<<" paper="<<paper<<endl;
}
};
int main()
{
int pa=123;
Stu s1(&pa,98);
s1.show();
int pa1=234;
Stu(&pa1,96);
cout << "Hello World!" << endl;
return 0;
}
完善Mystring
#include <iostream>
#include <string.h>
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);
cout<<"拷贝构造"<<endl;
}
MyString& operator=(const MyString &other) //拷贝赋值函数
{
this->str=new char[size+1];
this->size=other.size;
strcpy(str,other.str);
return *this;
}
bool isempty() //判空函数
{
if(size==0)
{
return true;
}
else
{
return false;
}
}
int getsize() //得到字符串长度
{
return size;
}
char *c_str() //得到字符串
{
return str;
}
char &at(int pos) //输出具体位置的字符
{
return str[pos-1];
}
const MyString operator+ (const MyString &R)const //运算符+重构
{
MyString temp;
temp.str=strcat(this->str,R.str);
temp.size=this->size+R.size;
return temp;
}
MyString & operator+=(const MyString &R) //运算符+=重构
{
this->size=this->size+R.size;
this->str=strcat(this->str,R.str);
return *this;
}
bool operator>(const MyString &R)const //运算符>重构
{
if(strcmp(this->str,R.str))
return true;
else
return false;
}
bool operator>=(const MyString &R)const
{
return strcmp(this->str,R.str);
}
friend ostream &operator<<(ostream &L, MyString &R);
friend istream &operator>>(istream &L,MyString &R);
char& operator[](const int index)
{
return str[index-1];
}
~MyString(){}
};
ostream &operator<<(ostream &L, MyString &R)
{
L<<R.str<<endl;
return L;
}
istream &operator>>(istream &L,MyString &R)
{
string s;
L>>s;
delete [] R.str;
R.size=s.size();
R.str=new char[s.size()+1];
strcpy(R.str,s.data());
return L;
}
int main()
{
MyString m1("hello");
MyString m2;
m2=m1;
cout<<m2.c_str()<<endl;
m1+=m2;
cout<<m1.c_str()<<endl;
MyString m3;
m3=m1+m2;
cout<<m3.c_str()<<endl;
if(m1>m2)
{
cout<<"m1>m2"<<endl;
}
cout<<m1.at(8)<<endl;
cout << "Hello World!" << endl;
return 0;
}
思维导图