2016-10-02 29 views
0

我想了解有關upcasting(child to parent)的static_cast。這對我沒有意義。我必須把一個孩子交給父母並且證明它。在網上查看一些代碼並參考書籍時,這就是我所擁有的。演示static_cast和它的目的?

Mustang *myMustang = new Mustang; 
Car *myCar = new Car; 

myMustang = static_cast<Mustang*>(myCar); 

但坦率地說,它沒有顯示任何東西。我沒有證實它甚至被鑄造。我試圖給Car類添加一個公共函數,並從孩子那裏調用它,但是......它顯然是繼承的。

這也意味着我目前在這種類型的上傳中沒有看到目的。

我的問題是,我如何驗證這個甚至鑄造,這種鑄造類型的目的是什麼?

更新:答案有點難以遵循,因爲我沒有這種類型的鑄造經驗,虛擬功能是一個模糊的記憶。我的朋友能夠幫助我。下面是代碼,以防其他人有相同的問題。

class Car { 
    public: 
    virtual void Greeting() { cout << "I am a car." << endl; }; 
}; 

class Focus : public Car{ 
    public: 
    void FocusGreeting() { cout << "Hello, I am a Ford Focus." << endl; } 
}; 

class Mustang : public Car { 
    public: 
    virtual void Greeting() override { cout << "I am a Ford Mustang." << endl; } 
}; 

// in main 
Mustang* myMustang = new Mustang; 
Car *myCar = new Car; 

myCar->Greeting(); 
cout << "Now "; 
myCar = static_cast<Car*>(myMustang); 

myCar->Greeting(); 
+1

除非'Mustang'是一個基類'Car',這是未定義的行爲 –

+2

你是向下傾斜的,而不是向上傾斜的。 –

+0

也嘗試使用可以通過派生類型重寫的虛函數。 –

回答

1

在CRTP圖案使用的一個示例:

#include <type_traits> 
// 
// the general concept of being able to accelerate 
template<class T> 
struct acceleratable 
{ 
    auto accelerate() { 
    static_assert(std::is_base_of<acceleratable<T>, T>::value, ""); 
    // turn this in to a T, since we know that *this really is a T 
    return static_cast<T*>(this)->do_accelerate(); 
    } 
}; 

// 
// something that implementes the concept of being able to accelerate 
struct car : acceleratable<car> 
{ 
private: 
    friend acceleratable<car>; 
    void do_accelerate() 
    { 
    // accelerate implementation here 
    } 
}; 

// 
// free function which accelerates anything that's acceleratable 
template<class Thing> 
auto accelerate(Thing& t) 
{ 
    t.accelerate(); 
} 

int main() 
{ 
    car c; 
    accelerate(c); 
} 
0

使用的另一非平凡例子是類型擦除

class S { 
    using FN = void(*)(void*); 

    template<typename T> 
    static void invoke(void *ptr) { 
     static_cast<T*>(ptr)->foo(); 
    } 

public: 
    template<typename T> 
    static S create(T *t) { 
     S s; 
     s.ptr = t; 
     s.f = &invoke<T>; 
     return s; 
    } 

    void run() { 
     f(ptr); 
    } 

private: 
    void *ptr; 
    FN f; 
}; 

struct A { void foo() {} }; 
struct B { void foo() {} }; 

int main() { 
    A a; 
    B b; 

    S s1 = S::create(&a); 
    S s2 = S::create(&b); 

    s1.run(); 
    s2.run(); 
}