通过派生类访问基类的值
问题描述:定义一个Teacher(教师)类和一个Student(学生)类,二者有一部分数据成员是相同的,例如num(号码),name(姓名),sex(性别)。编写程序,将一个Student对象(学生)转换为Teacher(教师)类,只将以上3个相同的数据成员移植过去。可以设想为: 一位学生大学毕业了,留校担任教师,他原有的部分数据对现在的教师身份来说仍然是有用的,应当保留并成为其教师的数据的一部分。
通过派生类访问基类的值,实际上就是变换的拷贝构造函数,红色部分是此功能的主要代码
#include<iostream>
#include<string>
using namespace std;
class Person
{
public :
int num;
string name;
char sex;
public :
Person(int nu,string na,char s): num(nu),name(na),sex(s) {}
Person()
{}
~Person() {}
};
class Teacher:public Person
{
private:
float fee;
public:
Teacher(int nu,string na,char s,float f): Person(nu,na,s),fee(f) {};
~Teacher() {}
Teacher(Person &p,float f)
{
num = p.num;
name = p.name;
sex = p.sex;
fee = f;
}
void print()
{
cout << "num: " << num << ",name: " << name << ",sex: " << sex << ",fee: " << fee << endl;
}
};
class Student:public Person
{
private:
float score;
public:
Student(int nu,string na,char s,float sc): Person(nu,na,s),score(sc) {};
Student() {}
~Student() {}
Student(Person &p,float s)
{
num = p.num;
name = p.name;
sex = p.sex;
score = s;
}
void print()
{
cout << "num: " << num << ",name: " << name << ",sex: " << sex << ",score: " << score << endl;
}
};
int main()
{
Person per(22,"tanjianwen",'m');
Student stu(per,98);
stu.print();
cout << "After become a teacher" << endl;
Teacher tea(per,998);
tea.print();
return 0;
}
之前用了下面的代码实现,虽然实现了要求,但是技巧性不强,只是通过成员函数来访问基类的值。
#include<iostream>
#include<string>
using namespace std;
class Person
{
public :
int num;
string name;
char sex;
public :
Person(int nu,string na,char s): num(nu),name(na),sex(s) {}
~Person() {}
};
class Teacher:public Person
{
private:
float fee;
public:
Teacher(int nu,string na,char s,float f): Person(nu,na,s),fee(f) {};
~Teacher() {}
void print()
{
cout << "num: " << num << ",name: " << name << ",sex: " << sex << ",fee: " << fee;
}
};
class Student:public Person
{
private:
float score;
public:
Student(int nu,string na,char s,float sc): Person(nu,na,s),score(sc) {};
~Student() {}
void print()
{
cout << "num: " << num << ",name: " << name << ",sex: " << sex << ",score: " << score;
}
int getNum()
{
return num;
}
string getName()
{
return name;
}
char getSex()
{
return sex;
}
};
int main()
{
Person per();
Student stu(23,"tanjianwen",'m',99);
stu.print();
cout << "After before a teacher" << endl;
/*Teacher tea;
tea = stu; 之前想这样去做的,但是绝对不行,属于不同的类的对象不能直接赋值 */
Teacher tea(stu.getNum(),stu.getName(),stu.getSex(),998);
tea.print();
return 0;
}
注:拷贝构造函数的一般格式:
Date(Data &d)
{
month = d.month;
day = d. day;
year = d.year ;
} //系统会默认给出这个函数,所以这段代码可写可不写
Date today(8,23,2005);
Date someday(today);
另外还可以通过赋值运算:
Date today(8,23,2005);
Date someday2;
someday2 = today;