2013-04-14 51 views
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() 

我怎麼能推派生類到基類無切片矢量? 如果沒有辦法解決這個問題,是否有任何等價的方法將多個派生類存儲到一個數組中,如對象?

回答

0

製作FUNC()爲虛基類

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

沒有切片正在發生。你需要讓func虛擬在Base

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

這告訴編譯器來查找func的動態類型Base*的。

0

您應該使用virtual functions

這裏是它如何工作的例子:

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"; 
} 

的main.cpp

#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()

相關問題