對不起,這是如此做作,但它涉及到一個作業問題。我明白爲什麼一切都會發生,除了我評論的那一行。有人可以向我解釋爲什麼C++正在做它正在做的事情嗎?C++繼承和方法重載混淆
感謝
#include <iostream>
using namespace std;
class X0 {};
class X1: public X0 {};
class X2: public X1 {};
class Y1
{
public:
virtual void f(int v) { cout << "Y1(int)" << endl; }
virtual void f(const X0 *x) { cout << "Y1(X0)" << endl; }
virtual void f(const X1 *x) { cout << "Y1(X1)" << endl; }
};
class Y2: public Y1
{
public:
virtual void f(const X0 *x) { cout << "Y2(X0)" << endl; }
virtual void f(const X1 *x) { cout << "Y2(X1)" << endl; }
virtual void f(const X2 *x) { cout << "Y2(X2)" << endl; }
};
int main(int argc, char * argv[])
{
X2 x2; X2 *X2Pointer = &x2;
Y2 y2; Y1 *Y1Pointer = &y2;
cout << "What is about to happen?" << endl;
//Y1 pointer points to a Y2 object.
//The Y2 class, upon being given an X2 pointer, should print Y2(X2)
Y1Pointer->f(X2Pointer);
cout << "Why did I just print Y2(X1)" << endl;
return 0;
}
C++沒有做任何事情。它是你這樣做的人 –
這幾乎是一個最小例子的*相反*。我們不需要演示你*做什麼*瞭解 - 只是你不知道的一個例子。 –