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;
}
你能描述的行爲從你期待什麼,上線有什麼不同? –
'Test2 :: print' *隱藏*'Test :: print'(並將其重新聲明爲'virtual') - Test2的所有孩子都繼承了'virtual'的功能 – UnholySheep
@UnholySheep,所以我無法訪問print從Test2直接或間接派生的任何類? –