【发布时间】:2017-03-23 15:04:01
【问题描述】:
我是 C++ 新手,在访问类中的变量时遇到了一些麻烦。从到目前为止我在这里读到的内容来看,创建全局变量是一种非常糟糕的做法,不要这样做,但我不知道如何移动对类的访问。
到目前为止,我的搜索已指示我在类中设置和获取函数,但我认为我只能在定义对象的块中使用它们。
基本上我想知道的是,如果我在 main() 中定义了一个类对象,然后在 main() 中调用一个函数,比如 gameLoop(),我如何在新函数中访问该对象而不使类对象成为全局对象。
例如:
#include "stdafx.h"
#include <iostream>
using namespace std;
#include <string>
class Word
{
private:
string m_word;
int m_length;
public:
void set(string word, int length)
{
m_word = word;
m_length = length;
}
};
void gameLoop()
{
word1.set(); //flags error as it cant acces the word1 object
//I want to be able to access word1 from here
//Not a copy because that wouldnt change the actual word1
//I dont want to define it in here because then it would be created again
//for each loop of gameLoop
}
int main()
{
Word word1;
int play = 1;
while (play ==1){
gameLoop();
}
return 0;
}
这是一个大大简化的版本,但出于游戏的目的,我希望将类存储在外部,但为了让 gameLoop 内的许多游戏功能能够访问和更改类对象。
【问题讨论】:
-
将
word1作为参数传递给gameLoop。 -
将其作为参数传递
gameLoop(Word word) -
作为参考可能更好 (
gameLoop(Word& word)) -
顺便说一句,您的措辞听起来有点混乱。你想访问一个对象而不是一个类和函数中没有定义的类(现在可以做到,但通常你不这样做)
-
或者你可以在
main之外声明Word word1;(在全局范围内)——但这通常是一种不好的做法