在c++中的类里,怎么将类“GameView”里的成员引用到类"GameOver"里
时间: 2024-03-04 11:49:45 浏览: 23
您可以在 `GameOver` 类的构造函数中传入 `GameView` 类的对象的引用,然后在 `GameOver` 类中就可以使用该对象的成员了。以下是示例代码:
```c++
// GameView 类定义
class GameView {
public:
int score;
};
// GameOver 类定义
class GameOver {
public:
GameOver(GameView& game) : m_game(game) {}
void showGameOver() {
cout << "Game Over! Your score is " << m_game.score << endl;
}
private:
GameView& m_game;
};
// 使用示例
int main() {
GameView gameView;
gameView.score = 100;
GameOver gameOver(gameView);
gameOver.showGameOver(); // 输出 "Game Over! Your score is 100"
return 0;
}
```
在 `GameOver` 类中,我们在构造函数中传入了 `GameView` 类的对象的引用,并在类成员变量 `m_game` 中保存了该引用。在 `showGameOver` 函数中,我们就可以使用 `m_game.score` 来访问 `GameView` 类中的 `score` 成员了。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)