我们知道在Java中是自动实现多态的,Java中规定重写的方法的访问权限不能缩小。那么在C++中我们实现多态的时候是否可以更改(缩小)访问权限呢?
经过测试,得到的答案如下:如果用基类指针指向派生类对象实现多态则虚函数的访问权限以基类中的访问权限为准。因此只要基类中的访问权限是public
就可以访问。派生类对象的访问权限以派生类中的为准。
这就意味这我们只要基类的虚函数权限是public
,我们就可以使用基类指针访问到派生类私有的虚函数。
具体样例:
#include<cstdio>
#include<iostream>
#include<string>using namespace std;class Employee
{
protected:string name, ID;Employee(string _name,string _ID):name(_name),ID(_ID){}void SetName(string _name){name = _name;}void SetID(string _ID){ID = _ID;}string GetName(){return name;}string GetID(){return ID;}
public:virtual double DisplaySalary(){return 0;}virtual void DisplayInform() = 0;
};class Manager :public Employee
{double salary;
public:Manager(string _name,string _ID,double _salary=5000):Employee(_name,_ID),salary(_salary){}double DisplaySalary(){return salary;}void DisplayInform(){cout << "经理信息:" << endl;cout << "姓名:" << name << "\tID:" << ID << "\t薪资:" << salary << endl;}void SetSalary(double _salary){salary = _salary;}
};class Technician :public Employee
{double wage, hours;
public:Technician(string _name, string _ID, double _wage = 100,double _hours=288):Employee(_name,_ID),wage(_wage),hours(_hours){}void SetWage(double _wage){wage = _wage;}void SetHours(double _hours){hours = _hours;}double DisplayWage(){return wage;}double DisplayHours(){return hours;}
private:double DisplaySalary(){return wage * hours;}void DisplayInform(){cout << "经理信息:" << endl;cout << "姓名:" << name << "\tID:" << ID << "\t薪资:" << DisplaySalary() << endl;}
};int main()
{Employee* p1 = new Manager("A", "01", 9000);Employee* p2 = new Technician("B", "02");Technician C("C", "03");p1->DisplayInform();p2->DisplayInform();cout << C.Employee::DisplaySalary() << endl;//直接访问会报错p2 = &C;cout << p2->DisplaySalary() << endl;return 0;
}
运行结果: