c++ - 如何避免虚拟关键字

标签 c++ inheritance

如何在没有虚拟键的情况下访问派生类的成员函数。

#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/

相关文章:

c++ - 无法使用初始化列表初始化 QQueue

c++ - QNetworkAccessManager 在 arch 上给出 ssl 错误

具有继承的 C++ 范围解析用法

sql - PostgreSQL继承: get the record class name

java - JPA - 我可以使用@DiscriminatorValue 创建一个没有自己的表的实体类吗?

c++ - 派生类调用基类中的模板函数时的链接问题

php - 图表比谷歌图表更好?

c++ - 当我对一个已经锁定的 pthread_mutex_t 执行 pthread_mutex_init 时会发生什么?

c++ - 解析字符串对失败。恶灵 x3 语法

java - 将父类(super class)转换为子类