#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;
}
你好,當通過Derived :: f2()調用f1()時,誰的函數被調用?
這個問題是考試的措辭之一,但它是我很難找到來形容它,並期待它在網上的正確途徑。
在行:
p2->f1();
輸出爲:
Base::f1()
Derived::f2()
Leaf::f1()
Leaf::f3()
中的F2
()有一個爲F1()的調用。誰會被稱爲? f1()的類型爲Base或f1()的Leaf? 從我所教的內容來看,編譯器總是在類型左邊尋找函數。 (Base * p2 = new Leaf(* p))但是在這裏我可以看到它轉到class Leaf的f1()。 我可以看到它是葉的,但不明白爲什麼...
感謝您的幫手!
從您的實際輸出中是不是明顯的答案? –
這個答案是一個事實。正如我在我的文章中所描述的,我不明白爲什麼它調用Leaf的f1()而不是Base的f1()... – EilonBom
你對vtable的問題是什麼? – curiousguy