在c++中的类里,怎么在类"GameOver"里使用类“GameView”里的成员int型变量score,GameOver与GameView在不同的分文件里
时间: 2024-03-05 12:51:13 浏览: 18
在类"GameOver"中使用类"GameView"中的成员int型变量score,可以通过在"GameOver"类中声明一个指向"GameView"类对象的指针,然后通过该指针访问"GameView"类中的score成员。
具体实现步骤如下:
1. 在"GameOver"类中声明一个指向"GameView"类对象的指针,如下所示:
```cpp
class GameView; // 前向声明GameView类
class GameOver {
private:
GameView* viewPtr; // 指向GameView类对象的指针
public:
// 构造函数,传入一个指向GameView类对象的指针
GameOver(GameView* view) : viewPtr(view) {}
// 在GameOver类中使用GameView类中的score成员
void showScore() {
std::cout << "Your score is: " << viewPtr->score << std::endl;
}
};
```
2. 在"GameView"类中声明"GameOver"类为友元类,以便让"GameOver"类能够访问"GameView"类中的score成员,如下所示:
```cpp
class GameView {
private:
int score;
public:
// 将GameOver类声明为友元类
friend class GameOver;
};
```
3. 在程序的主函数中创建"GameView"类对象和"GameOver"类对象,并将"GameView"类对象的地址作为参数传递给"GameOver"类对象的构造函数,如下所示:
```cpp
int main() {
GameView view;
GameOver over(&view);
over.showScore();
return 0;
}
```
这样,在"GameOver"类中就可以通过指向"GameView"类对象的指针访问"GameView"类中的score成员了。
相关推荐
![exe](https://img-home.csdnimg.cn/images/20210720083343.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)