#include <iostream>
#include <string>
using namespace std;
class Base {
public:
Base(const string& s): str(s) {cout<<"Base::ctor\n";}
Base(const Base& b): str(b.str) {cout<<"Base::copy ctor\n";}
virtual ~Base() {cout<<"Base::dtor\n";}
void f1() {cout<<"Base::f1()\n"; f2();} //2 orders
virtual void f2() {cout<<"Base::f2()\n";}
private:
string str;
};
class Derived : public Base {
public:
Derived(const string& s): Base(s)
{cout<<"Derived::ctor\n";}
Derived(const Derived& d): Base(d)
{cout<<"Derived::copy ctor\n";}
~Derived() {cout<<"Derived::dtor\n";}
virtual void f1() {cout<<"Derived::f1()\n"; f2();}
void f2() {cout<<"Derived::f2()\n"; f1();} //jumps from here to Leaf's f1()
};
class Leaf : public Derived {
public:
Leaf(const string& s): Derived(s)
{cout<<"Leaf::ctor\n";}
Leaf(const Leaf& dd): Derived(dd)
{cout<<"Leaf::copy ctor\n";}
~Leaf() {cout<<"Leaf::dtor\n";}
void f1() {cout<<"Leaf::f1()\n"; f3();}
void f3() {cout<<"Leaf::f3()\n";}
};
int main() {
Leaf * p = new Leaf("Hello");
Base * p2 = new Leaf(*p);
p2->f1();
delete p2;
delete p;
return 0;
}
你好,
这个问题是一个考试用词,但我很难找到正确的方式来描述它并在网上寻找它。
排队 :
p2->f1();
输出是:
Base::f1()
Derived::f2()
Leaf::f1()
Leaf::f3()
在派生的 f2() 中有对 f1() 的调用。谁会被召唤?Base 类型的 f1() 还是 Leaf 类型的 f1()?根据我所学到的,编译器总是在左边的类型中寻找函数。(Base* p2 = new Leaf(*p) ) 但是在这里我可以看到它转到了 Leaf 类的 f1() 。我可以看到它是Leaf的,但不明白为什么......
感谢帮手!