【问题标题】:Use Members of One Class in Another Class (OOP)在另一个类中使用一个类的成员 (OOP)
【发布时间】:2020-03-14 19:32:10
【问题描述】:

我有两个课程 Instructor 和 Game。

Instructor.h

class Instructor
{
    int instrID;

public:
    Instructor();
    void showGameStatus();
    int createGame();                           
    vector<int> createGames(int numberOfGames); 
};

游戏.h:

class Game {

private:                            
    int gID;                        
    int instrID;                    
    int pFactID;                    
public:

    Game() {                // default constructor
        gID = 0;
        instrID = 0;
        pFactID = 0;

    };

这些在 Instructor.cpp 中

void Instructor::showGameStatus()
{

}

int Instructor::createGame()
{
    Game g;
}

CreateGame() 初始化游戏。我希望在调用 showGameStatus() 时可以打印出之前初始化的游戏 g 的所有属性(例如 gId、InstrId)等。

是否可以通过其他方法访问游戏 g 的属性?

【问题讨论】:

    标签: c++ class oop c++11


    【解决方案1】:

    应该这样做。类 Instructor 应继承类 Game: 类教练::公共游戏{ 你的代码在这里 }

    【讨论】:

    • 继承不构成此问题的正确 OO 解决方案的一部分。教师不是游戏,或者反之亦然。
    【解决方案2】:

    简短的回答是:不。

    更长的答案是:如果我理解正确,您想要完成的问题是Game 类型的对象gInstructor::createGame 成员函数范围内的局部变量持有.一旦该功能“完成”,即本地范围结束,具有 automatic storage 的对象将被销毁。它消失了。我不知道int 意味着你返回是什么意思,但不管它做什么,它都不包含Game 类型的对象。

    现在,您可能希望您的createGame 将某种类型的句柄返回给实际的Game 对象。根据您的具体设置,您的工作是选择如何传递这样的对象。例如,一种方式可能是这样的:

    Game Instructor::createGame() const { // 1
      Game g;
      // do stuff with g, perhaps?
      return g;
    }
    

    另一个可能是:

    std::unique_ptr<Game> Instructor::createGame() const { // 2
      auto gptr = std::make_unique<Game>();
      // do stuff with gptr, perhaps?
      return gptr;
    }
    

    或者另一个:

    std::size_t Instructor::createGame() { // 3
      // Instructor has a member std::vector<Game> games
      games.emplace_back();
      // do stuff with games.back()
      return games.size()-1;
    }
    

    还有无数其他方法可以传递对象。

    无论你选择什么,你必须传递一些东西来识别哪个你正在谈论的Game对象回到你的@987654333 @ 函数,如果您计划让多个 Game 对象四处飞来飞去(我假设您会这样做)。

    auto some_handle = instructor.createGame();
    // ... later ...
    instructor.showGameStatus(some_handle);
    

    这一切都成立,如果你想要多个对象否则您可能只想将对象添加为 Instructor 类型的成员:

    class Instructor {
      private:
        Game game;
      public:
        Instructor() : game() {}
        // no createGame function, it is superfluous
        void showGameStatus() const {
          game.some_output_function();
        }
    };
    

    【讨论】:

      【解决方案3】:

      只需将 Instructor 类继承到 Game 类中,然后做你的工作......

      【讨论】:

      • 您的解决方案适用于该问题,但您应该指定如何更改给定代码/其中的某些部分。
      • “继承”是什么意思?继承不构成此问题的适当 OO 解决方案的一部分。教师不是游戏,或者反之亦然。
      猜你喜欢
      • 1970-01-01
      • 2013-05-17
      • 2013-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多