在另一个班级(OOP)中使用一个班级的成员

时间:2020-03-14 19:32:10

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

我有两个班的讲师和游戏。

Instructor.h

class Instructor
{
    int instrID;

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

Game.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()时可以打印出先前初始化的Game g的所有属性(例如gId,InstrId)。

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

3 个答案:

答案 0 :(得分:1)

这应该做到。班主任应继承班级游戏: 课堂讲师::公共游戏{ 您的代码在这里 }

答案 1 :(得分:0)

简单的答案是:不。

更长的答案是这样的:如果我理解正确,您想完成什么,问题是类型g的对象Game由{范围内的局部变量保存{1}}成员函数。一旦“完成”该功能,即本地作用域结束,具有 automatic storage 的对象将被销毁。它消失了。我不知道Instructor::createGame意味着您返回,但是不管它做什么,它都不会保存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功能,如果您计划有一个以上的showGameStatus对象飞来飞去(我想是的话)。

Game

如果您想要多个对象,那么这一切都是正确的。 否则,您可能只想将该对象添加为auto some_handle = instructor.createGame(); // ... later ... instructor.showGameStatus(some_handle); 类型的成员:

Instructor

答案 2 :(得分:-1)

只需将讲师类继承到游戏类中并完成您的工作...