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?
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.
The solution is to use virtual inheritance (assuming you need multiple inheritance) as:
class Manager : public virtual Employee
Hope you note the virtual
keyword here. :-)
Everybody has already covered virtual inheritance, but I'd suggest reading the C++ FAQ as well.
http://www.parashift.com/c++-faq-lite/multiple-inheritance.html
You need a virtual inheritance in this case:
#include <iostream>
#include <string>
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 virtual Employee
{
public:
string getname()
{
return ("Manager" + name);
}
Manager(string name2) : Employee(name2){}
Manager() : Employee(){}
};
class Supervisor : public Manager,public virtual Employee
{
public:
Supervisor(string name2) : Manager(name2) , Employee(name2){}
Supervisor() : Manager() , Employee(){}
string getname()
{
return ("Supervisor" + Employee::getname());
}
};
This problem is also known as Diamond inheritance problem: http://en.wikipedia.org/wiki/Diamond_problem
Supervisor
contains two objects of type Employee, the direct one and the one over Manager. It is ambiguous to call Employee
methods on a Supervisor
in consequence (which Employee should be called?). You might want to employ virtual multiple inheritance instead.
来源:https://stackoverflow.com/questions/10454874/c-multiple-inheritance