如何在没有虚拟键的情况下访问派生类的成员函数。
#include<iostream>
using namespace std;
class Employee{
public:
void what(){
cout<<"Employee"<<endl;
}
};
class Secretary:public Employee{
public:
void what(){
cout<<"Secretary"<<endl;
}
};
class Manager:public Employee{
public:
void what(){
cout<<"Manager"<<endl;
}
};
class Director:public Manager{
public:
void what(){
cout<<"Director"<<endl;
}
};
void f(Employee*);
int main(){
Employee a;
Manager b;
Director c;
Secretary d;
f(&a);
f(&b);
f(&c);
f(&d);
return 1;
}
void f(Employee *a){
a->what();
}
它总是打印“Employee”。我想打印每个对象的类名。 a.what() 正确打印它的类名。但是我必须在这个赋值上使用指针和 f(Employee *) 函数。
最佳答案
好的,这是一个完全人为的方法,它不使用 virtual
,灵感来自 @Stephen 的评论 - 它只是将文本存储在基类中,以便当函数 f 对类进行切片时数据仍然存在。
#include<iostream>
using namespace std;
class Employee{
public:
std::string name;
Employee(std::string name = "Employee"):name(name){}
void what(){
cout<<name<<endl;
}
};
class Secretary:public Employee{
public:
Secretary(std::string name = "Secretary"):Employee(name){}
};
class Manager:public Employee{
public:
Manager(std::string name = "Manager"):Employee(name){}
};
class Director:public Manager{
public:
Director(std::string name = "Director"):Manager(name){}
};
void f(Employee*);
int main(){
Employee a;
Manager b;
Director c;
Secretary d;
f(&a);
f(&b);
f(&c);
f(&d);
return 1;
}
void f(Employee *a){
a->what();
}
关于c++ - 如何避免虚拟关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37042654/