【发布时间】:2013-05-13 12:43:28
【问题描述】:
我在 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;
}
编译器返回结果:1413.
我有点困惑,因为我认为正确的结果应该是 1414(作为虚拟函数)。你如何解释这个程序行为?
【问题讨论】:
-
不要将
;放在#include指令的末尾。 -
@Fabien 我对编译好的程序感到惊讶。
标签: c++ inheritance vector