前言
C++中拷贝构造函数的深拷贝和浅拷贝是一个很重要的问题,在使用组合时,我们应该自定义拷贝构造函数,实现深拷贝。下面是一个实现组合对象的深拷贝的例子。
问题描述
读取"score.txt",将其中的人名全部进行加密处理,并计算平均分,最后写入另一个文件scored.txt;
例如:
//score.txt //scored.txt
姓名,年龄,成绩 姓名,年龄,成绩
abc, 19, 80 -----> bcd, 19, 80
bcd, 18, 90 cde, 18, 90
cde, 20, 87 def, 20, 87
def, 18, 90 efg, 18, 90
最高分姓名:cde, efg
最高分:90
平均分:88
要求:
1.用纯C++语法实现,原文件不得做更改;
2.体现封装的思想,并进行类的嵌套;
3.必须使用无参构造函数、含参构造函数、拷贝构造函数;
4.实现中需体现出深拷贝的必要性;
5.需使用静态成员变量和静态成员函数。
源程序
StuAttr.h
#ifndef STUATTR
#define STUATTR
#include <iostream>
using namespace std;
/*
声明学生的属性类
将age和score作为学生的属性封装进Attribute类中
*/
class StuAttr{
private:
int age; //年龄
int score; //分数
public:
StuAttr(); //无参构造函数
~StuAttr(); //析构函数
StuAttr(int a, int s); //带参构造函数
StuAttr(const StuAttr &a); //拷贝构造函数
void setAttr(int a, int s); //设置属性
void print(); //打印属性
int getScore(); //获得分数
int getAge(); //获得年龄
};
#endif
Student.h
#ifndef STUDENT
#define STUDENT
#include<string>
#include "StuAttr.h"
using namespace std;
/*
声明学生类
*/
class Student{
private:
string name; //名字
StuAttr attr; //类的嵌套定义,将age和score作为学生的属性封装进Attribute类中
public:
static string classRoom; //班级,定义为静态数据成员
Student(); //无参构造函数
~Student(); //析构函数
Student(string n, int a, int s); //带参构造函数
Student(string n, StuAttr &a); //带参构造函数
Student(const Student &stu); //拷贝构造函数
Student& operator=(const Student &stu); //重载赋值运算符
void setAttr(string n, int a, int s); //设置属性
int getAge(); //获得年龄
int getScore(); //获得分数
string getName(); //获得名字
static string getClassRoom(); //获得班级
void print(); //打印属性
void encodeNmae(); //加密名字
};
#endif
StuAttr.cpp
#include "StuAttr.h"
StuAttr::StuAttr(){
age = 0;
score = 0;
}
StuAttr::~StuAttr(){
}
StuAttr::StuAttr(int a, int s){
age = a;
score = s;
}
StuAttr::StuAttr(const StuAttr &a){
cout << "age:" << a.age << " score:"<<a.score << " 调用拷贝构造函数StuAttr(const StuAttr &a)" << endl;
age = a.age;
score = a.score;
}
void StuAttr::setAttr(int a, int s)