我有一个继承自基类的Derived类。基类具有一个将基对象作为参数的方法。我想使用这种方法,但要传递Derived类的对象,但是会收到这样的错误:
没有匹配的函数可以调用Base :: method(Derived)[...]候选者是Base :: method(Base)
最小示例:
#include <iostream>
#include <vector>
using namespace std;
class A {
public:
int bar;
void sum(vector<A>& a){
cout<<bar+a[0].bar<<endl;
}
};
class B : public A {
public:
B(int i){
bar = i;
}
};
int main(void){
B b1(1);
B b2(2);
vector<B> v;
v.push_back(b2);
b1.sum(v);
}
编译器结果
main.cpp: In function 'int main()':
main.cpp:27:13: error: no matching function for call to 'B::sum(std::vector<B>&)'
b1.sum(v);
^
main.cpp:27:13: note: candidate is:
main.cpp:10:14: note: void A::sum(std::vector<A>)
void sum(vector<A> a){
^
main.cpp:10:14: note: no known conversion for argument 1 from 'std::vector<B>' to 'std::vector<A>'