Vit*_*i K 1 c++ inheritance vector
我在c ++上有以下代码:
#include <iostream>;
#include <vector>;
class A
{
public:
A(int n = 0) : m_n(n) { }
public:
virtual int value() const { return m_n; }
virtual ~A() { }
protected:
int m_n;
};
class B
: public A
{
public:
B(int n = 0) : A(n) { }
public:
virtual int value() const { return m_n + 1; }
};
int main()
{
const A a(1);
const B b(3);
const A *x[2] = { &a, &b };
typedef std::vector<A> V;
V y;
y.push_back(a);
y.push_back(b);
V::const_iterator i = y.begin();
std::cout << x[0]->value() << x[1]->value()
<< i->value() << (i + 1)->value() << std::endl;
system("PAUSE");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编译器返回结果:1413.
我有点困惑,因为我认为正确的结果将是1414(作为虚函数).你如何解释这个程序的行为?
您正在切片对象,为了获得多态性,您需要使用a pointer或a reference.此示例尽可能保持与原始示例的关系,并使用pointer将按您的意愿执行操作:
const A a(1);
const B b(3);
typedef std::vector<const A*> V;
V y;
y.push_back(&a);
y.push_back(&b);
V::iterator i = y.begin();
std::cout << (*i)->value() << std::endl ;
++i ;
std::cout << (*i)->value() << std::endl ;
Run Code Online (Sandbox Code Playgroud)