0

以下の2番目で選択したもの以外GetJ()に、クラスのメンバー関数にアクセスするためのより簡単な方法はありますか?Derivedstd::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;
}
4

2 に答える 2

0

GetIとGetJは、Derivedから派生していますが、2つの異なるクラスに属していると思い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。ただし、関数を仮想として宣言する場合は、アップキャストとダウンキャストについて気にする必要はありません。ベースポインタ自体はあなたのために働くのに十分です

于 2012-08-01T04:20:43.243 に答える
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; }
}
于 2012-07-25T19:38:52.833 に答える