#include <iostream>
using namespace std;
class Person
{
const string name;
int age;
char sex;
public:
Person():name("zhangsan"){/*cout << "Person的无参构造" << endl;*/ }
Person(const string name,int age,char sex):name(name),age(age),sex(sex)
{
// cout << "Person的有参构造" << endl;
}
~Person()
{
// cout << "Person的析构函数" << endl;
}
void show()
{
cout << " name=" << name << " age=" << age << " sex=" << sex <<endl;
}
Person(const Person &other):name(other.name)/*,age(other.age),sex(other.sex)*/
{
this->age=other.age;
this->sex=other.sex;
}
Person &operator=(const Person &other)
{
if(this!=&other)
{
//const string nmae 构造函数时已经初始化
this->age=other.age;
this->sex=other.sex;
cout << "Person的拷贝赋值" <<endl;
}
return *this;
};
};
class Stu
{
Person A;
double *p;
public:
Stu():p(new double)
{
cout << "Stu的无造函数" << endl;
}
Stu(const string name,int age,char sex,double score):A(name,age,sex),p(new double(score))
{
cout << "Stu的有参构造" << endl;
}
~Stu()
{
delete p;
cout << "Stu的析构函数" << endl;
}
void show()
{
cout << "p=" << p;
cout << " *p=" << *p << endl;
A.show();
}
Stu(const Stu &other):p(new double(*(other.p))),A(other.A){}
Stu &operator=(const Stu &other)
{
this->A=other.A;
*(this->p)=*(other.p);
cout << "Stu的拷贝函数" << endl;
}
};
int main()
{
// Stu t1;
// t1.show();
// Stu t2("lisi",3,'s',99.9);
// t2.show();
Person t3("wangwu",17,'m');
Person t4;
t4=t3;
t3.show();
t4.show();
Stu t5("wangwu",17,'m',88.8);
t5.show();
Stu t6=t5;
t6.show();
Stu t7("kenn",28,'w',77.7);
Stu t8;
t8=t7;
t7.show();
t8.show();
return 0;
}
#include <iostream>
#include <cstring>
#include <iomanip>
#include <stdio.h>
using namespace std;
class myString
{
char *str;
int size;
public:
myString():str(new char[32]){cout << "myString无参构造"<<endl;}
myString(char *str):str(new char[32])
{
strcpy(this->str,str);
this->size=strlen();
cout << this->str << endl;
cout << "myString有参构造"<<endl;
printf("%p\n",this->str);
}
myString(const myString &other):str(new char[32])
{
strcpy(this->str,other.str);
this->size = other.size;
cout << "myString拷贝构造"<<endl;
printf("%p\n",this->str);
}
myString &operator=(const myString &other)
{
if(&other!=this)
{
strcpy(this->str,other.str);
this->size=other.size;
cout << "myString拷贝赋值"<<endl;
printf("%p\n",this->str);
}
return *this;
}
~myString()
{
delete []str;
str=nullptr;
cout << "myString析构函数"<<endl;
}
void show()
{
cout << "str=" << str << " size=" << size << endl;
}
int empty()
{
string s1=str;
return s1.empty();
}
int strlen()
{
string s1=str;
return s1.size();
}
char &at(int pos)
{
string s1=str;
return s1.at(pos);
}
};
int main()
{
myString p1;
//p1.show();
char str[32]="hello nihao";
myString p2(str);
p2.show();
myString p3=p2;
p3.show();
myString p4;
p4=p2;
p4.show();
return 0;
}