2012-07-25 8 views
0

有沒有更簡單的方法來訪問Derived類中的成員函數GetJ(),而不是在下面第二個std::cout中選擇的成員函數GetJ()在下面的例子中,是否有更簡單的方法來訪問成員函數GetJ()?

#include <iostream> 
#include <memory> 

class Base 
{ 
    int i; 

    public: 

    Base(int k) : i(k) {} 
    int GetI() { return i; } 
}; 

class Derived : public Base 
{ 
    int j; 

    public: 
    Derived(int u) : Base(10) { j = u; } 
    int GetJ() { return j; }  
}; 

int main() 
{ 
    std::unique_ptr<Base> uptr(new Derived(5)); 
    std::cout << uptr->GetI() << std::endl; 
    std::cout << static_cast<Derived*>(uptr.get())->GetJ() << std::endl; 
} 
+1

順便說一句,一個簡單的'static_cast' [工作得很好](http://ideone.com/txJxm)。 – chris 2012-07-25 19:26:47

+0

@chris:就是說,只要你確定*知道基指針指向那個特定的派生類。 – Xeo 2012-07-25 19:28:53

+0

@Xeo,是的,但即使你不這樣做,reinterpret_cast也不是你的最佳選擇。 – chris 2012-07-25 19:29:45

回答

0

到以前的版本問題:

首先,reinterpret_cast絕對錯誤的方式來做到這一點。試試這個:

struct A 
{ 
    char x[10]; 
    A():x{9}{} 

}; 

class Derived : public A, public Base 
{ 
// your code here 
}; 

而不是你的Derived的定義。

static_cast在這裏可以正常工作。

當前的狀態:

通常當你要使用由指針Derived功能Base類,你要虛函數:

class Base 
{ 
    //.... 
    virtual int GetJ() const = 0; 
    // or virtual int GetJ() const { return -1;} if Base should be created itself. 

    virtual ~Base(){} //oh, and don't forget virtual destructor! 
}; 

class Derived: public Base 
{ 
    //... 
    virtual int GetJ() const { return j; } 
} 
+0

從你的例子看來,你可以在基類中使用純虛函數。 – chris 2012-07-25 19:42:21

+0

@chris,我也想過了。我不確定是否應該使用'Base' ... – Lol4t0 2012-07-25 19:44:32

+0

@chris它可以在'Base'中作爲純虛函數與'GetJ()'一起工作,也就是說,如果我替換第二個'std :: cout'與'std :: cout << uptr-> GetJ()<< std:; endl;'我打印5張!如果您提交答案,我會接受。 – WaldB 2012-07-25 19:49:07

0

我相信格提及GetJ屬於儘管Derived源自Base,但兩種不同的類別。現在這個問題依賴於如何訪問它。

Derived* p = new Derived(5)); 
std::cout << p->GetI() << std::endl; 
std::cout << p->GetJ() << std::endl; 

上面的代碼應該很好,因爲你已經從地點派生出來了。

但如果你真的想與

Derived* p = new Derived(5)); 
Base* pBase = p; 
std::cout << pBase->GetI() << std::endl; 
std::cout << p->GetJ() << std::endl; 

上班以上方法只是因爲功能不virtual。但是如果你將函數聲明爲虛擬的,你實際上不必擔心向上轉換和向下轉換。基地指針本身就足以爲你工作