这个标题已被多次使用,但在搜索了大约 5-6 个示例后,我找不到任何与我的问题相匹配的内容:
我有一个简单的继承实践。
类A是一个基类,类B和C继承自它:
class A {
};
class B : public A { public: int i; };
class C : public A { public: int j; };
还有一个类 P 包含这样的重载函数:
class P
{
public:
void change(B *b)
{
b->i =1;
}
void change(C *c)
{
c->j =1;
}
};
当我使用如下功能时:
int main()
{
A *b = new B();
A *c = new C();
P p;
p.change(b);
p.change(c);
return 0;
}
它给出了一个错误说:
inherit2.cpp: In function ‘int main()’:
inherit2.cpp:37:12: error: call of overloaded ‘change(A*&)’ is ambiguous
inherit2.cpp:37:12: note: candidates are:
inherit2.cpp:21:7: note: void P::change(B*) <near match>
inherit2.cpp:21:7: note: no known conversion for argument 1 from ‘A*’ to ‘B*’
inherit2.cpp:26:7: note: void P::change(C*) <near match>
inherit2.cpp:26:7: note: no known conversion for argument 1 from ‘A*’ to ‘C*’
inherit2.cpp:38:12: error: call of overloaded ‘change(A*&)’ is ambiguous
inherit2.cpp:38:12: note: candidates are:
inherit2.cpp:21:7: note: void P::change(B*) <near match>
inherit2.cpp:21:7: note: no known conversion for argument 1 from ‘A*’ to ‘B*’
inherit2.cpp:26:7: note: void P::change(C*) <near match>
inherit2.cpp:26:7: note: no known conversion for argument 1 from ‘A*’ to ‘C*’
如果您能帮我解决问题,我将不胜感激。拉赫曼