#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;
}
Здравствуйте,Кто вызывает функцию при вызове f1() через Derived :: f2()?
Этот вопрос экзамен сформулирован один, но это очень трудно для меня, чтобы найти правильный путь, чтобы описать его и искать его в Интернете.
в строке:
p2->f1();
выход:
Base::f1()
Derived::f2()
Leaf::f1()
Leaf::f3()
в Derived f2() есть призыв к f1(). кто будет называться? f1() типа Base или f1() листа? Из того, чему меня учили, компилятор всегда ищет функцию в типе слева. (Base * p2 = new Leaf (* p)) Но здесь я вижу, что он переходит в f1() класса Leaf. Я вижу, что это Лиф, но не понимаю, почему ...
спасибо за помощников!
Не является ли ответ очевидным из вашего фактического результата? –
Этот ответ - факт. Как я описал в своем посте, я не понимаю, почему он вызывает f1(), а не base f1() ... – EilonBom
Что вы думаете о vtable? – curiousguy