0

エンジン(Unity3D)で見た動作をC++プロジェクトに実装したいと思います。

次のコードはC#(Unityの言語)です。

using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {

    void Update() {
        //Update is called every frame
    }
}

MonoBehaviorソースにアクセスできないため、Update()はこのように実装できる仮想関数であると推測できます。

同じ動作をC++で再現したいと思います。ループを作成するmain()と、スーパーオブジェクトはUpdate()そのループで呼び出されるメソッドを持ち、そのすべての子はこのスーパーオブジェクトを継承し、実装Update()して使用できるようにする必要があります。

あいまいな質問だとは思いますが、どこでも答えを探しましたが、見つかりませんでした。

次に例を示します。

class Base
{
 public:
     virtual void Update();
};

class Object: public Base
{
 public:
     void Update();
};

void main()
{
     Base* base;
     while(1)
     {
        base->Update();
     }
}

その結果、ObjectのUpdate()はBaseを介して呼び出されるはずです。私は100%上記のコードが機能しないので、いくつかのアイデアが必要です。

4

3 に答える 3

5

C++にはインターフェイスがありません。純粋仮想メソッドを使用して抽象クラスを作成します。

class MonoBehaviour 
{
    virtual void Update() = 0;
};

class your_class : MonoBehaviour 
{
    void Update() 
    { 
        // implement here. 
    }
};
于 2013-01-06T20:05:51.397 に答える
0

子クラスメソッドと基本クラスメソッドのシグネチャが同じではない可能性があります。つまり、名前は同じですが、返されるものが異なるか、パラメータが異なります。これは、常に基本クラスのメソッドを呼び出す1つの方法です。

または、main関数で子クラスオブジェクトではなく、基本クラスオブジェクトを作成しているだけの場合もあります。main関数にブレークを入れて、Updateを呼び出しているオブジェクトの実際のタイプを調べます。

The code you've posted should work as desired. It doesn't matter if the base class is abstract or not. I prefer to make it concrete and throw exceptions in the methods that should be =0 for the sake of easiness when implementing the children classes (I don't have to implement the full behavior from the start, just the methods I am focused on and which I am testing; so it goes incrementally).

And yes, stick with public inheritance.

EDIT: Or there might be object slicing involved if you have something like this:

Derived* d_ptr = new Derived();
Base b = *d_ptr; // object slicing, d's methods will become Base methods;
Base* b_ptr = &b;
b_ptr->Update(); // will call Base::Update()
于 2013-01-06T23:32:12.270 に答える
0

First things first. The example you provided will not work firstly because you forgot the instantiation of your pointer. You probably meant smth like this:

 Base* base = new Object;
 while(1)
 {
    base->Update();
 }

これで邪魔になりません。この概念は、期待どおりに機能するはずです。他の人がすでに指摘しているように、Updateがベースの仮想関数をオーバーライドする場合は、ObjectクラスでUpdateを呼び出す必要があります。c++11と呼ばれる素敵なものがありoverrideます。これは、ベース内の一部の仮想関数をオーバーライドすることを期待する関数の宣言の後に配置するキーワードです。非仮想関数overrideを実行しようとするとコンパイラが文句を言うので、使用することをお勧めします。overrideこれにより、コードでエラーが発生する可能性が低くなります。

于 2015-12-27T13:12:07.240 に答える