在下面的示例中是否有更简单的方法来访问成员函数GetJ()?

时间:2012-07-25 19:19:35

标签: c++ c++11 derived-class unique-ptr

是否有更简单的方法可以访问GetJ()课程中的成员函数Derived,而不是下面第二个std::cout中选择的成员函数?

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

2 个答案:

答案 0 :(得分: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; }
}

答案 1 :(得分:0)

我认为GetI和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。但是如果你将这些函数声明为虚拟函数,那么你真的不必担心向上转换和向下转换。基指针本身足以为你工作