Heyo,當涉及調用對象作爲它們的父類型時,我對如何重寫方法有點困惑。當使用父類型時覆蓋C++方法
這裏是我的示例代碼:
#include <iostream>
#include <cstdlib>
#include <vector>
using namespace std;
class A {
public:
A() {
std::cout << "Made A.\n";
}
void doThing() {
std::cout << "A did a thing.\n";
};
};
class B : public A {
public:
B() {
std::cout << "Made B.\n";
}
void doThing() {
std::cout << "B did a thing.\n";
};
};
class C : public A {
public:
C() {
std::cout << "Made C.\n";
}
void doThing() {
std::cout << "C did a thing.\n";
};
};
int main(int argc, char** argv) {
std::cout << "\n";
std::cout << "Make objects: \n";
A a;
B b;
C c;
std::cout << "Call objects normally: \n";
a.doThing();
b.doThing();
c.doThing();
std::cout << "Call objects as their parent type from a vector: \n";
vector<A> vect;
vect.push_back(a); vect.push_back(b); vect.push_back(c);
for(int i=0;i<vect.size();i++)
vect.data()[i].doThing();
return 0;
}
,這裏是輸出我得到:
Make objects:
Made A.
Made A.
Made B.
Made A.
Made C.
Call objects normally:
A did a thing.
B did a thing.
C did a thing.
Call objects as their parent type from a vector:
A did a thing.
A did a thing.
A did a thing.
在另一種語言(如Java)相同的代碼會產生這樣的輸出:
Make objects:
Made A.
Made B.
Made C.
Call objects normally:
A did a thing.
B did a thing.
C did a thing.
Call objects as their parent type from a vector:
A did a thing.
B did a thing.
C did a thing.
總之,如何在C++中實現第二個輸出?
Righo!更改爲「矢量 vect;」並推送數據爲「vect.push_back(&b);」結果輸出我想要的。謝謝! – 2015-02-05 17:05:10