我遇到了用 C++ 编写的这段代码:
#include<iostream>
using namespace std;
class Base {
public:
virtual int fun(int i) { cout << "Base::fun(int i) called"; }
};
class Derived: public Base {
private:
int fun(int x) { cout << "Derived::fun(int x) called"; }
};
int main()
{
Base *ptr = new Derived;
ptr->fun(10);
return 0;
}
输出:
Derived::fun(int x) called
在以下情况下:
#include<iostream>
using namespace std;
class Base {
public:
virtual int fun(int i) { }
};
class Derived: public Base {
private:
int fun(int x) { }
};
int main()
{
Derived d;
d.fun(1);
return 0;
}
输出:
Compiler Error.
谁能解释为什么会这样?在第一种情况下,通过对象调用私有函数。