问题
#include <iostream>
#include <vector>
using namespace std;
class Parent {
public:
Parent();
void method();
};
class Child: public Parent {
public:
Child();
void method();
};
int main() {
vector<Parent> v;
v.push_back(Parent());
v.push_back(Child());
v[0].method();
v[1].method();
return 0;
}
Parent::Parent() {}
void Parent::method() {
cout << "Parent." << endl;
}
Child::Child() {}
void Child::method() {
cout << "Child." << endl;
}
Basically I'd expect that program to print
Parent.
Child.
but it prints this instead:
Parent.
Parent.
C++ surprises me yet again :).
Why does this happen? What can I do to call Child::method for instances of Child in the vector, and Parent::method for instances of Parent?
I'm using gcc:
gcc version 4.6.1 20110819 (prerelease) (GCC)
like this:
g++ -Wall -Wextra -c main.cpp
g++ -Wall -Wextra -o main main.o
回答1:
You are encountering the slicing problem.
vector<Parent>.push_back()
copies its argument, so it invokes Parent::Parent(const Parent &)
(i.e. the copy constructor)*.
This is really no different to:
Parent x[10];
x[0] = Parent();
x[1] = Child();
* Or it might be Parent::operator=(const Parent &)
, i.e. copy-assignment. I'm tired, and I can't remember which it needs.
回答2:
The vector stores Parent
s, not Children
s.
If you want to take advantage of polymorphism, store pointers instead... but be damned sure that it's what you want.
来源:https://stackoverflow.com/questions/7313622/calling-method-of-child-class-on-a-vector-of-parent-class