C++中的向量容器和静态绑定?

nab*_*bil 0 c++ inheritance virtual-functions vector static-binding

有人可以解释为什么i->value()(i + 1)->value()打印1和3不是1和4喜欢 x[0]->value() << x[1]->value()

#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); //a.m_n=1
    const B b(3); //b.m_n=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;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

谢谢

Igo*_*nik 5

y.push_back(b);创建一个实例,A该实例是A子对象的副本b,并将其推送到向量上.B矢量上没有实例,也没有实例,因此B::value()不会调用.阅读有关对象切片的内容