关于多重继承,有一个误区,如果多重继承的各个基类中有一个相同名字的成员函数,则通过派生类的对象调用时会产生错误,无论这个函数在各个基类中的形参类型是否一样。(注意:不要把从多个派生类中继承而来的同名但参数类型不同的函数看成是这些函数在派生类中重载)
#include <iostream>
#include <string>
using namespace std;
class person
{
public:
person(string na) : name(na) {}
void display(int i)
{
cout << name << endl;
}
private:
string name;
};
class student
{
public:
student(int a) : age(a) {}
void display(string s)
{
cout << age << endl;
}
private:
int age;
};
class school : public person, public student
{
public:
school(string na, int a, int n) : person(na), student(a), num(n) {}
private:
int num;
};
int main()
{
string str("heloo");
school s("hello", 10, 1);
s.display(str);
return 0;
}
以上这段程序会报错。
不过对于这个,我倒是有一点疑问,明明参数类型不同,调用为什么会出错呢?
希望有理解的回个帖。Thank you!
但是 如果将主函数中的调用语句改为如下形式则正确.
s. person::display(10);
s. student::display(str);
这样就正确了。