1、定义一个Person类,有const修饰的成员name;int成员age,char类型的成员sex,定义一个Stu类,包含Person 成员,double *成员,要求:写出Person和Stu的构造和析构函数,每个类至少写出两种构造函数,实现一个公有的show函数,输出Stu类中属性和Person类中属性的值。在上一个练习的基础上,写出Person类和Stu类的拷贝构造函数。
完成拷贝赋值函数
#include <iostream>
using namespace std;
class person
{
const string name;
int age;
char sex;
public:
person ():name("wanger"),age(20),sex('n')
{
cout << "无参构造" <<endl;
}
person(string name,int age, char sex):name(name),age(age),sex(sex)
{
// this->name=name;
// this->age=age;
// this->sex=sex;
cout << "person的有参构造" << endl;
}
person(const person &other):name(other.name),age(other.age),sex(other.sex)
{
// this->name = other.name;
// this->age = other.age;
// this->sex=other.sex;
cout << "person的拷贝构造函数" << endl;
}
void show();
~person ()
{
cout << "person的析构函数" << endl;
}
person &operator = (const person &other)
{
if(&other!=this)
{
this->age=other.age;
this->sex=other.sex;
cout << "person的拷贝赋值函数 " << endl;
}
return *this; //通过this指针返回自身的引用
}
};
//fun函数的参数和返回值的位置都会调用拷贝构造函数
person fun(person q)
{
return q;
}
void person::show()
{
cout << "name=" << name << endl;
cout << "age=" << age <<endl;
cout << "sex=" << sex << endl;
}
class stu
{
person p1;
double *p;
public:
stu():p1("wangssan",21,'m'),p(new double)
{cout << "stu的无参构造" << endl;}
stu(string name,int age,char sex,double socre):p1(name,age,sex),p(new double(socre))
{
cout << "stu的有参构造" << endl;
}
void show()
{
p1.show();
}
~stu()
{
delete p;
cout << "stu的析构函数" << endl;
}
stu(const stu &other):p(new double(*(other.p))),p1(other.p1)
{cout << "stu的拷贝构造函数" << endl;}
stu &operator=(const stu &other)
{
*(this->p)=*(other.p);
this->p1=other.p1;
cout << "stu的拷贝赋值函数" << endl;
return *this;
}
};
int main()
{
// person *p;
// p=new person;
// p->show();
// delete p;
// person t1("lisi",19,'m');
// t1.show();
// stu *x;
// x=new stu;
// x->show();
// stu s1;
// s1.show();
// cout << "***************" <<endl;
// stu s2("zhangwu",29,'m',90);
// s2.show();
// return 0;
person pd("liwu",19,'m');
pd.show();
person pd1;
pd1=pd;
pd1.show();
person *p3=new person(pd1);
p3->show();
fun(pd);
}
#include <iostream>
#include <cstring>
using namespace std;
class myString
{
private:
char *str; //记录c风格的字符串
int size; //记录字符串的实际长度
public:
myString():str(new char),size(size)
{
cout<< "mySring 的无参构造函数" << endl;
} //无参构造
myString(char s1,int size):str(new char(s1)),size(size)
{
cout<< "myString的有参构造函数" << endl;
}//有参构造
//拷贝构造
myString(const myString &other):str(new char(*(other.str)))
{
this->size=other.size;
cout << "myString的拷贝构造函数" << endl;
}
//拷贝赋值函数
myString &operator =(const myString &other)
{
if(&other!=this)
{
this->size=other.size;
*(this->str)=*(other.str);
cout << "myString的拷贝构造函数" << endl;
}
return *this;
}
//析构函数
~myString()
{
delete str;
cout << "myString的析构函数" << endl;
}
//判空函数
void empty(string b);
//size函数
void c_str(int a);
//c_str函数
void c_str(string c);
//at函数
char &at(int pos);
};
int main()
{
return 0;
}