2017-05-23 61 views
0

下面的代碼中的派生類Test2和Test3不是虛擬類型,那麼爲什麼函數被覆蓋以及如何阻止它發生? 上午 - >我是一個新手,所以這個問題可能是愚蠢的抱歉。多級繼承中的多態性

#include <iostream> 
using namespace std; 

class Test { 
public: 
    int a, b, c; 
    Test(int x, int y, int z) { 
    a = x; 
    b = y; 
    c = z; 
    } 
    void print() { cout << "a= " << a << "b= " << b << "c= " << c << endl; } 
}; 

class Test2 : public Test { 
public: 
    int d, e; 
    Test2(int a, int b, int c, int x, int y) : Test(a, b, c) { 
    d = x; 
    e = y; 
    } 
    virtual void print() { cout << "d= " << d << "e= " << e << endl; } 
}; 

class Test3 : public Test2 { 
public: 
    int f; 
    Test3(int a, int b, int c, int d, int e, int x) : Test2(a, b, c, d, e) { 
    f = x; 
    } 
    void print() { cout << "f= " << f << endl; } 
}; 

class Test4 : public Test3 { 
public: 
    int g; 
    Test4(int a, int b, int c, int d, int e, int f, int x) 
     : Test3(a, b, c, d, e, f) { 
    g = x; 
    } 
    void print() { cout << "g= " << g << endl; } 
}; 

int main() { 
    Test *test; 
    Test2 *test2; 
    Test3 *test3; 
    Test4 test4(1, 2, 3, 4, 5, 6, 7); 
    test = &test4; 
    test2 = &test4; 
    test3 = &test4; 
    test->print(); 
    test2->print(); 
    test3->print(); 
    test4.print(); 
    return 0; 
} 
+2

你能描述的行爲從你期待什麼,上線有什麼不同? –

+3

'Test2 :: print' *隱藏*'Test :: print'(並將其重新聲明爲'virtual') - Test2的所有孩子都繼承了'virtual'的功能 – UnholySheep

+0

@UnholySheep,所以我無法訪問print從Test2直接或間接派生的任何類? –

回答

1

Test2::printvirtual,因此上一指針print調用Test2或一個指針,指向從Test2導出將使用對象的運行時類型來確定調用哪個函數的類。在你的情況下,該對象的運行時類型是Test4,因此它會調用Test4::print。這是virtual函數的要點。

如果你想顯式調用不同版本的print你可以這樣做,e.g test3->Test3::print();