- 1.memcpy的使用
- 2.this指针
- 3.关于清理内存的方法和位置
student .h文件部分
#include <iostream>
#include <string>
using namespace std;
class student
{
private:
float* scores;//学生的分数数组
int scorecnt;//学生成绩个数
public:
student();
~student();
void initscores();//初始化学生数组,默认分配一个数组空间
void addscore(float);//添加学生成绩
void show();
};
student.cpp部分
#include "student.h"
#include <cstring> //memcpy的头文件
student::student()
{
cout << "调用默认构造" << endl;
initscores();//初始化学生成绩
}
//注意void类型
void student::initscores()
{
this->scores = new float[1];//scores成为数组
this->scorecnt = 1;
}
void student::addscore(float score)
{
this->scores[this->scorecnt - 1] = score;
//创建一个新数组,分配scorecnt+1个空间
//把原数组复制到新数组中
//scorecnt++
//scores指向新数组
float* newscores = new float[scorecnt + 1];
float* oldscores = scores;//存旧的的地址
memcpy(newscores, scores, sizeof(float) * scorecnt);
scorecnt++;
scores = newscores;//数组地址改变
delete oldscores;//要把旧的scores在上面new的旧数组给delete掉
}
student::~student()
{
delete this->scores;//因为前面创建了,析构函数就要清理掉内存
//但实际上前面已经把scores的内存指向oldscores并清除掉了
}
void student::show()
{
for (int i = 0;i < scorecnt - 1;i++)
{
cout << this->scores[i] << '\t';
}
}
main.cpp
#include "vip.h"
#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
float x=1;
vip* ptr_user1=new student();
cout << "请输入学生分数" << endl;
//输入0结束输入
while (x!= 0)
{
cin >> x;
ptr_user1->addscore(x);
}
ptr_user1->show();
delete ptr_user1;
}
2.引用的使用完成两人总分比较
//这里只书写相关部分
student.h
class student
{
public:
//书写函数,返回得分最高对象
vip& gethighest(vip&);//注意返回的是对象
float gettotal();//计算学生总分
}
student.cpp
student& student::gethighest(student& other)
{
注意这里!!
//分别计算两个学生的成绩
if (this->gettotal() > other.gettotal())
{
return *this; //返回当前对象的引用
}
else
{
return other;
}
}
//下面是个简单的算总分的函数
float student::gettotal()
{
float sum = 0.0;
for (int i = 0;i < scorecnt - 1;i++)
{
sum += scores[i];
}
return sum;
}
main.cpp
student* ptr_user1 = new student();
student user2;
//调用比较方法 student& gethighest(student&); 注意返回的是对象,所以要student一个top
//gethighest函数返回值要么是*this,要么是other (参数是student& gethighest(student& other))
//注意传值,形参是student& other,传值是*ptr_user1
//总之传的是vip类型,例如写法2;
student& top = user2.gethighest(*ptr_user1);
//写法2 student& top = ptr_user1 -> gethighest(user2)
//因为gethighest返回值是other,而other类型是&类型,那接收类型也用student&