gpt4 book ai didi

c++ - 误解了 vector 中的虚函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:22:34 25 4
gpt4 key购买 nike

我在 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(作为虚函数)。你如何解释这个程序行为?

最佳答案

你是slicing对象,为了获得多态性,您需要使用 pointerreference。此示例尽可能接近您的原始示例并使用 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 ;

关于c++ - 误解了 vector 中的虚函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16522365/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com