在基类向量上调用虚函数 [英] Calling a virtual function on a vector of base classes

查看:30
本文介绍了在基类向量上调用虚函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一些代码来重现问题:

I created some code to reproduce the problem:

#include "stdafx.h"
#include <iostream>
#include <vector>

class A
{
protected:
    int m_X;
public:
    A() { 
        std::cout << "in A ctor" << std::endl; 
        m_X = 0;
    }
    virtual void printX(){ std::cout << "in A " << m_X << std::endl; }
};

class B : public A
{
public:
    B() {
        std::cout << "in B ctor" << std::endl; 
        m_X = 1;
    }
    virtual void printX(){ std::cout << "in B " << m_X << std::endl; }
};

class As
{
public:
    void AddA( const A &a ){ m_As.push_back( a ); }
    void PrintXs()
    {
        for ( auto a : m_As )
        {
            a.printX();
        }
    }
private:
    std::vector<A> m_As;
};

int _tmain(int argc, _TCHAR* argv[])
{
    As as;
    B b;
    as.AddA( b );
    as.PrintXs();
    system("pause");
    return 0;
}

输出结果是:

在演员

在 B 中

在 A 1

我想要在 B 1"而不是在 A 1".我确信我对虚拟的理解是有缺陷的.我必须如何更改代码以调用 B PrintX()?请注意,会有其他类从 A 继承,所以我真的不想编写静态调用.

I want "in B 1" instead of "in A 1". I'm sure my understanding of virtual is flawed. How must I change the code to call the B PrintX()? Note that there will be other classes that inherit from A so I really don't want to code a static call.

谢谢.

推荐答案

你正在做的事情叫做 切片.这是您获取派生类的对象并修剪掉父类中不存在的所有对象并将其分配给父类的地方.

What you're doing is called slicing. This is where you take an object of a derived class and trim off everything that is not in the parent and assign it to the parent.

您想要做的是使用多态来做您所解释的事情.为此,请将向量从对象的副本更改为对象的 ptr.

What you want to do is use polymorphism to do what you explained. To do this, change your vector from a copy of the object, to a ptr to the object.

如果对更多细节感兴趣,请使用提供的链接,其中包含的信息似乎非常完整.

If interested in more details, please use the links provided, the information included in them seems to be very complete.

这篇关于在基类向量上调用虚函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆