思维导图
作业
设计一个Per类,类中包含私有成员:姓名、年龄、指针成员身高、体重,再设计一个Stu类,类中包含私有成员:成绩、Per类对象p1,设计这两个类的构造函数、析构函数和拷贝构造函数。
代码
#include <iostream>
using namespace std;
class Per
{
private:
string name;
int age;
double *height;
double *weight;
public:
Per() {cout << "Per无参构造" << endl;}
Per(string n,int a,double h,double w):name(n),age(a),height(new double(w)),weight(new double(w))
{
cout << "Per有参构造" << endl;
}
Per(const Per &other):name(other.name),age(other.age),height(other.height),weight(other.weight)
{
cout << "Per拷贝构造" << endl;
}
~Per(){
cout << "Per析构" << endl;
delete height;
delete weight;
}
void show()
{
cout << name << endl;
cout << age << endl;
cout << *height << endl;
cout << *weight << endl;
}
};
class Stu
{
private:
double score;
Per p1;
public:
Stu() {cout << "Stu无参构造" << endl; }
Stu(string n,int a,double h,double w,double s):p1(n,a,h,w),score(s)
{
cout << "Stu有参构造" << endl;
}
Stu(const Stu &other):p1(other.p1),score(other.score)
{
cout << "Stu拷贝构造" << endl;
}
~Stu()
{
cout << "Stu析构" << endl;
}
void show()
{
p1.show();
cout << score << endl;
}
};
int main()
{
Stu s1("cheryl",18,180,160,98);
Stu s2=s1;
s1.show();
s2.show();
return 0;
}
运行结果
一些重点
new\delete与malloc\free的区别
1.new\delete本质上是关键字效率较高,而malloc、free属于函数调用,效率低
2.malloc申请空间时以字节为单位,而new申请空间时,以数据类型作为单位
3.使用new申请空间时可以对其初始化,而malloc申请时不可用
4.malloc函数申请出来的是void*类型的地址,使用时需要强转为所需类型,而new申请什么类型的返回就是什么类型的指针
5.new、delete申请是否空间分单个和连续。但是malloc、free不考虑
6.malloc申请空间时,需要使用sizeof计算所需空间大小。而new、delete不需要计算
7.new申请对象空间时会调用构造函数 ,而malloc不会
8.delete释放对象空间时,会调用析构函数,而free不会