在Java里,没有多重继承,在C++里面有,但是,在用的时候,要小心。先看一个错误程序:

#include <iostream>
using namespace std;

class Father
{
public:
	void claim()
	{
		cout << "Father is good!" << endl;
	}
};

class Mother
{
public:
	void claim()
	{
		cout << "Mother is good!" << endl;
	}
};

class Child : public Father, public Mother
{
};

int main()
{
	Child c;
	c.claim(); // 二义性

	return 0;
}
      可以改为:

#include <iostream>
using namespace std;

class Father
{
public:
	void claim()
	{
		cout << "Father is good!" << endl;
	}
};

class Mother
{
public:
	void claim()
	{
		cout << "Mother is good!" << endl;
	}
};

class Child : public Father, public Mother
{
};

int main()
{
	Child c;
	c.Father::claim();
	c.Mother::claim();

	return 0;
}
     

       另外,在菱形继承时,也会出现类似问题,解决方式是采用虚继承。





本文转载:CSDN博客