1
class Base
{
    public :
        void func()
        {
            cout << "Base func()" << endl;
        }
};

class DerivedA : public Base
{
    public :
        void func()
        {
            cout << "Derived A func()" << endl;
        }
};

class DerivedB : public Base
{
    public :
        void func()
        {
            cout << "Derived B func()" << endl;
        }
};

void main()
{
    DerivedA a;
    DerivedB b;

    vector<shared_ptr<Base>> temp;
    temp.push_back(make_shared<DerivedA> (a));
temp.push_back(make_shared<DerivedB> (b));

    for(auto ptr : temp)
    ptr->func();
}

输出是

Base func()
Base func()

但我所期望的是

Derived A func()
Derived B func()

如何在不切片的情况下将派生类推入基类向量?如果没有办法解决这个问题,是否有任何等效的方法可以将多个派生类存储到一个类似对象的数组中?

4

3 回答 3

4

没有切片发生。您需要在以下位置进行func虚拟化Base

virtual void func()
{
    cout << "Base func()" << endl;
}

这告诉编译器查找funca 的动态类型Base*

于 2013-04-14T17:56:22.133 回答
0

在基类中将 func() 设为虚拟

class Base
{
    public :
        virtual void func()
        {
            cout << "Base func()" << endl;
        }
};
于 2013-04-14T18:03:52.857 回答
0

您应该使用虚函数

这是它如何工作的示例:

virtual_functions.h

#pragma once

class Base {
public:
    virtual void virtual_func();   // virtual function.
    void non_virtual_func();       // non-virtual function.
};

class Derived : public Base {
public:
    void virtual_func();          // virtual function.
    void non_virtual_func();      // non-virtual function.
};

virtual_functions.cpp

#include "virtual_functions.h"

#include <iostream>
using namespace std;

void Base::virtual_func() {
    cout << "Base::virtual_func\n";
}

void Base::non_virtual_func() {
    cout << "Base::non_virtual_func()\n";
}


void Derived::virtual_func() {
    cout << "Derived::virtual_func\n";
}

void Derived::non_virtual_func() {
    cout << "Derived::non_virtual_func()\n";
}

主文件

#include "virtual_functions.h"

int main() {
    // Declare an object of type Derived.
    Derived aDerived;

    // Declare two pointers,
    // one of type Derived * 
    // and the other of type Base *,
    // and initialize them to point to derived.

    Derived *pDerived = &aDerived;
    Base    *pBase    = &aDerived;

    // Call the functions.
    pBase->virtual_func();        // Call virtual function.
    pBase->non_virtual_func();    // Call nonvirtual function.
    pDerived->virtual_func();     // Call virtual function.
    pDerived->non_virtual_func(); // Call nonvirtual function.

    return 0;
}

输出应该是:

派生::virtual_func()
基::non_virtual_func()
派生::virtual_func()
派生::non_virtual_func()

于 2013-04-15T06:56:53.240 回答