繁体   English   中英

具有迭代器和继承的STL容器

[英]STL Container with iterator and inheritance

这是一个示例C ++问题,用于找出结果。

#include <iostream>
#include <vector>

class A
{
public:
    A(int n = 0) : m_n(n) { }

public:
    virtual int f() const { return m_n; }
    virtual ~A() { }

protected:
    int m_n;
};

class B
    : public A
{
public:
    B(int n = 0) : A(n) { }

public:
    virtual int f() 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({ a, b });
    V::const_iterator i = y.begin();

    std::cout << x[0]->f() << x[1]->f()
              << i->f() << (i + 1)->f() << std::endl;

    return 0;
}

我期望的输出是“ 1 4 1 4”,但是正确的答案是“ 1 4 1 3”。

从上面,

x[0]->f()

也就是说,x [0]只是指向类型A的对象的指针,调用f()返回1。

x[1]->f()

即,x [1]只是指向类型A的对象的指针(指向派生类对象的基类指针),并调用派生类f()返回(3 + 1)= 4

我不确定将对象a和b添加到向量容器中并通过const_iterator进行继承迭代时的行为

i->f()

我可以理解这一点,因为我只是指向第一个元素(即对象a)的指针。

但是这里会发生什么呢?

(i + 1)->f()

我的理解是,它指向序列中的下一个元素,即对象b和通过派生类指针调用f()应该调用其成员函数而不是基类的成员函数?

向量y包含两个类型为A对象。 不是B型。 构造它时,它会复制ab ,同时 b 切片 因此(i + 1)->f()bA部分的那个副本上调用A::f() ,得到3。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM