【问题标题】:Is there a simpler way to access the member function GetJ() in the example below?在下面的示例中,是否有更简单的方法来访问成员函数 GetJ()?
【发布时间】:2012-07-24 07:31:27
【问题描述】:

除了下面第二个std::cout 中选择的方法之外,还有更简单的方法可以访问Derived 类中的成员函数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_castworks just as fine
  • @chris:也就是说,只要你明确知道基指针指向那个特定的派生类。
  • @Xeo,是的,但即使您不这样做,reinterpret_cast 也不是您的最佳选择。
  • @chris:天哪,我读到 dynamic_cast... 哦,天哪。
  • @chris 感谢您的建议。我已经编辑了代码。

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


【解决方案1】:

至上一版问题:

首先,reinterpret_cast绝对是错误的做法。试试这个:

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

};

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

而不是您的 Derived 定义。

static_cast 在这里可以正常工作。

到当前状态:

但是通常当你打算通过指向Base类的指针来使用Derived功能时,你需要虚函数:

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

【讨论】:

  • 从您的示例来看,您可以在基类中使用纯虚函数。
  • @chris 它与GetJ() 一起作为Base 中的纯虚函数使用,即,如果我用std::cout &lt;&lt; uptr-&gt;GetJ() &lt;&lt; std:;endl; 替换第二个std::cout,我会打印5 个!如果您提交答案,我会接受。
【解决方案2】:

我相信 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。但是,如果您将函数声明为虚拟函数,则您真的不必为向上转换和向下转换而烦恼。基指针本身足以为您工作

【讨论】:

    猜你喜欢
    • 2019-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多