1.声明 :
class 派生类名:【继承方式】基类名
{
派生类新增的数据成员和成员函数
}
例如:
class Employee:public Person
{
public:
void setDepartment( string d)
{
dapartment = d;
}
void setSalary(float s)
{
salary = s;
}
void print1()
{
cout<<"dapartment:"<<dapartment<<endl;
cout<<"salary:"<<salary<<endl;
}
private:
string dapartment;
float salary;
};
下面是派生类的具体应用:
#include <iostream>
#include <cstring>
using namespace std;
class Person
{
public:
void setName( string n) { name = n; }
void setAge(int a) { age = a; }
void setSex(char s) { sex = s; }
void print()
{
cout<<"name:"<<name<<endl;
cout<<"age:"<<age<<endl;
cout<<"sex:"<<sex<<endl;
}
protected:
string name;
int age;
char sex;
};
class Employee:public Person
{
public:
void setDepartment( string d)
{
dapartment = d;
}
void setSalary(float s)
{
salary = s;
}
void print1()
{
cout<<"dapartment:"<<dapartment<<endl;
cout<<"salary:"<<salary<<endl;
}
private:
string dapartment;
float salary;
};
int main()
{
Person a;
a.setName("Alice");
a.setAge(30);
a.setSex('F');
a.print();
Employee b;
b.setName("Bob"); // 设置 Person 类的属性
b.setAge(25);
b.setSex('M');
b.setDepartment("Sales");
b.setSalary(5000.0);
b.print(); // 输出 Person 类的信息
b.print1();
return 0;
}