2014-07-07 25 views
11

Występują problemy z automatycznym typowaniem w kolejności od shared_ptr dziedziczonych klas.std :: shared_ptr and Inheritance

Moja struktura klas wygląda następująco: podstawowa klasa Base i dwie pochodne klasy Derived1 i Derived2.

// Base class 
class Base { 
protected: 
    ... 
    ... 
public: 
    Base() = default; 
    virtual ~Base() = default; 
    virtual void run() = 0; 
    ... 
    ... 
}; 

// Derived class 
class Derived1: Base { 
protected: 
    ... 
    ... 
public: 
    Derived1() = default; 
    virtual ~Derived1() = default; 
    void run() {...} 
    ... 
    ... 
}; 

// Derived class 
class Derived2: Base { 
protected: 
    ... 
    ... 
public: 
    Derived2() = default; 
    virtual ~Derived2() = default; 
    void run() {...} 
    ... 
    ... 
}; 

Mam funkcja doSomething()

void doSomething(std::shared_ptr<Base> ptr) { 
    ptr->run(); 
    ... 
} 

I wywołania funkcji z klas pochodnych jak tak -

doSomething(make_shared<Derived1>()) 
doSomething(make_shared<Derived2>()) 

Ale pojawia się błąd mówiąc -

no viable conversion from 'shared_ptr<class Derived1>' to 'shared_ptr<class Base>' 
no viable conversion from 'shared_ptr<class Derived1>' to 'shared_ptr<class Base>' 

Co czy robię źle? Czy korzystanie z static_pointer_cast jest bezpieczne tylko w przypadku typu Base? Like -

doSomething(static_pointer_cast<Base>(make_sahred<Derived2>())) 

ROZWIĄZANIE My bad ... Problemem było to, że dziedziczy klasę bazową prywatnie.

Odpowiedz

5

O ile mogę powiedzieć, kod, które zostały zaprezentowane kompiluje grzywny: http://ideone.com/06RB2W

#include <memory> 

class Base { 
    public: 
     Base() = default; 
     virtual ~Base() = default; 
     virtual void run() = 0; 
}; 

class Derived1: public Base { 
    public: 
     Derived1() = default; 
     virtual ~Derived1() = default; 
     void run() {} 
}; 

class Derived2: public Base { 
    public: 
     Derived2() = default; 
     virtual ~Derived2() = default; 
     void run() {} 
}; 

void doSomething(std::shared_ptr<Base> ptr) { 
    ptr->run(); 
} 

int main() { 
    doSomething(std::make_shared<Derived1>()); 
    doSomething(std::make_shared<Derived2>()); 
} 
+0

Który kompilator nie używa? Dostaję błąd na najnowszym Apple Clang ... – subzero

+10

Przepraszam, moje złe ... Dziedziczyłem prywatnie w moim kodzie! To był naprawdę debiutancki błąd! – subzero

+1

Czy shared_ptr automatycznie (bez rzutowania) konwertuje do klasy podstawowej shared_ptr? Czy mają taką samą liczbę referencyjną? – abhiarora

Powiązane problemy