【发布时间】:2016-10-31 23:33:43
【问题描述】:
假设我有这部分代码:
#include<iostream>
using namespace std;
class A {
public:
virtual int f(const A& other) const { return 1; }
};
class B : public A {
public:
int f(const A& other) const { return 2; }
virtual int f(const B& other) const { return 3; }
};
void go(const A& a, const A& a1, const B& b) {
cout << a1.f(a) << endl; //Prints 2
cout << a1.f(a1) << endl; //Prints 2
cout << a1.f(b) << endl; //Prints 2
}
int main() {
go(A(), B(), B());
system("pause");
return 0;
}
我能理解为什么前两个会打印2。但我不明白为什么最后一个打印也是2。为什么它不喜欢B中的重载函数?
【问题讨论】:
-
因为您使用
A引用来调用f。而A不知道f(const B& other)
标签: c++ overriding overloading