#include <iostream>
using namespace std;
class Person
{
private:
string name;
int age;
char sex;
public:
Person():name("zhangsan"),age(18),sex('m'){
cout<<"Person无参构造"<<endl;
}
Person(const string name,int age,char sex):name(name),age(age),sex(sex){
cout<<"Person有参构造"<<endl;
}
Person(const Person &other):name(other.name){
cout<<"拷贝构造"<<endl;
this->age=other.age;
this->sex=other.sex;
}
Person &operator=(const Person &other){
if(&other!=this){
this->name=other.name;
this->age=other.age;
this->sex=other.sex;
cout<<"拷贝赋值"<<endl;
}
return *this;
}
~Person(){
cout<<"Person析构函数"<<endl;
}
void show();
};
void Person::show(){
cout<<"name:"<<name<<endl;
cout<<"age:"<<age<<endl;
cout<<"sex:"<<sex<<endl;
}
class Stu
{
private:
Person p1;
double *p2;
public:
Stu():p1("lisi",17,'m'),p2(new double(5.2)){
cout<<"Stu无参构造"<<endl;
}
Stu(string name,int age,char sex,double *p2):p1(name,age,sex),p2(p2){
cout<<"Stu有参构造"<<endl;
}
// 深拷贝
Stu(const Stu &other):p1(other.p1),p2(new double(*(other.p2))){
cout<<"Stu拷贝构造"<<endl;
}
//拷贝赋值
Stu &operator=(Stu &other){
if(&other!=this){
cout<<"拷贝赋值"<<endl;
this->p1=other.p1;
*(this->p2)=*(other.p2);
}
return *this;
}
~Stu(){
cout<<"Stu析构函数"<<endl;
delete p2;
p2=nullptr;
}
void show();
};
void Stu::show(){
p1.show();
cout<<"p2:"<<p2<<endl<<"*p2:"<<*p2<<endl;
}
int main()
{
Person p1;
Person p2={"wang",18,'f'};
p2=p1;
p1.show();
p2.show();
Stu s1;
Stu s2={"zhang",15,'m',new double(3.3)};
s2=s1;
s1.show();
s2.show();
return 0;
}
#include <iostream>
#include <cstring>
using namespace std;
class Mystring
{
private:
char *str;
int size;
public:
//无参构造
Mystring():str(nullptr),size(0){
cout<<"无参构造"<<endl;
}
//有参构造
Mystring(const char *str){
size=strlen(str);
this->str=new char[size+1];
strcpy(this->str,str);
cout<<"有参构造"<<endl;
}
//拷贝构造
Mystring(const Mystring &other){
size=other.size;
str=new char[size+1];
strcpy(str,other.str);
cout<<"拷贝构造"<<endl;
}
//拷贝赋值
Mystring &operator=(const Mystring &other){
if(&other!=this){
delete []str;
size=other.size;
str=new char[size+1];
strcpy(str,other.str);
}
return *this;
}
//析构函数
~Mystring(){
delete [] str;
cout<<"析构函数"<<endl;
}
//判空函数
int empty(){
if(0==size){
return 1;
}
else{
return 0;
}
}
//size函数
int len(){
return size;
}
//c_str函数
char *c_str(){
return str;
}
//at函数
char &at(int pos){
if(pos>=size){
return *(str);
}
return *(str+pos);
}
};
int main()
{
Mystring s1("world");
Mystring s2(s1);
Mystring s3;
s3=s2;
cout<<s3.c_str()<<endl;
cout<<s3.at(5)<<endl;
return 0;
}