有沒有更簡單的方法來訪問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;
}
順便說一句,一個簡單的'static_cast' [工作得很好](http://ideone.com/txJxm)。 – chris 2012-07-25 19:26:47
@chris:就是說,只要你確定*知道基指針指向那個特定的派生類。 – Xeo 2012-07-25 19:28:53
@Xeo,是的,但即使你不這樣做,reinterpret_cast也不是你的最佳選擇。 – chris 2012-07-25 19:29:45