C ++多继承 [英] C++ multiple inheritance

查看:189
本文介绍了C ++多继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请不要质疑这里代码中的工人的奇怪的层次结构,我不知道为什么有人会想要这样的东西,但我决定给自己一个多重继承的练习,只是为了确保我完全理解它。

Please don't question the really odd hierarchy of workers in this code here, I have no idea why anyone would want something like this, but I decided to give myself an exercise in Multiple Inheritance, just to be sure I fully understood it. So here's the result.

using namespace std;

class Employee
{
protected:
    string name;
public:
    string getname()
    {
        return name;
    }
    void setname(string name2)
    {
        name = name2;
    }
    Employee(string name2)
    {
        name = name2;
    }
    Employee(){}
};

class Manager : public Employee
{
public:
    string getname()
    {
        return ("Manager" + name);
    }
    Manager(string name2) : Employee(name2){}
    Manager() : Employee(){}
};

class Supervisor : public Manager,public Employee
{
public:
    Supervisor(string name2) : Manager(name2) , Employee(name2){}
    Supervisor() : Manager() , Employee(){}
    string getname()
    {
        return ("Supervisor" + Employee::getname());
    }
};

希望你明白我在这里想做什么。我得到一些关于派生类'监督员'和基本类'雇员'之间的模糊转换。那么我该怎么办?

Hopefully you're understanding what I'm trying to do here. I'm getting something about an "ambiguous conversion between derived class 'Supervisor' and base class 'Employee.'" So what do I do?

推荐答案

其实,你定义 Supervisor 类的方式,它的对象将有两个类型 Employee ,每个都来自它的基类。这是造成问题。

Actually, the way you have defined Supervisor class, its object will have two subjects of type Employee, each coming from it base classes. That is causing problem.

解决方案是使用虚拟继承(假设您需要多重继承)as:

The solution is to use virtual inheritance (assuming you need multiple inheritance) as:

class Manager : public virtual Employee 

希望你在这里注意到 virtual 关键字。 : - )

Hope you note the virtual keyword here. :-)

这篇关于C ++多继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆