在C ++中使用extern作为类实例

时间:2015-01-01 20:50:32

标签: c++ inheritance extern

我想拥有我的引擎类的全局实例,以便在创建actor的实例时可以隐式地将actor添加到我的actor管理器中。为简单起见,我将所有代码都归结为一个文件。

我的麻烦是使用extern,因为我还没有定义我的课程时如何使用extern。我想也许c ++会允许我使用父类作为类型,但没有运气。

#include <iostream>

namespace Engine { class Abstract {};};
extern Engine::Abstract *engine;

namespace Engine { class Actor {
public:
  Actor(){
    engine->actors->add(this);
  }
};};

namespace Engine { class ActorManager {
public:
  void add(){
    std::cout << "Actor.." << std::endl;
  }
};};

namespace Engine { class Base : Abstract {
public:
  ActorManager *actors;
  void run() {
    actors = new ActorManager();
    this->setup();
  }
  virtual void setup(){}
};};


class Player : Engine::Actor {};

class MyGame : public Engine::Base {
  void setup(){
    Player *player;
    player = new Player();
  }
};

MyGame *engine = new MyGame;
int main(int argc, const char ** argv)
{
  engine->run();
  delete engine;
  return 0;
}

这就是我在ruby中实现这一目标的方法

$game = nil

module Engine
  class Actor
    def initialize
      $game.actors.add
    end
  end

  class ActorManager
    def add
      puts 'adding an actor'
    end
  end

  class Base
    attr_accessor :actors
    def initialize
      self.actors = ActorManager.new
    end
  end
end

class Player < Engine::Actor
end

class Game < Engine::Base
  def run
    Player.new
  end
end

$game = Game.new
$game.run

1 个答案:

答案 0 :(得分:0)

标头仅适用于大多数基类,因此它会编译但不会链接(如您所知)

namespace Engine {
    // header info only - nothing is defined here

    class Actor {
    }; 

    // interface for ActorManager
    class ActorManager {
    public:
        void add(const Actor*);
    };
    extern ActorManager * global_pManager;

    // interface for Game
    class Game : public ActorManager {
    public:
        virtual ~Game(){};         // you need a virtual destructor
        virtual void setup() = 0;  // abstract interface
        virtual void run() = 0;    // abstract interface
    };
};

// header for your game and player logic
class Player : public Engine::Actor {
};
class MyGame : public Engine::Game {
public:
    void setup();
    void run();
};

int main(int argc, const char ** argv)
{
    // scope of main is a better way to control the lifetime of this object
    MyGame engine;        

    // here's the global pointer you requested
    Engine::global_pManager = static_cast<Engine::ActorManager*>(&engine);

    engine.run();
    return 0;
}