2

我是 C++ 新手,正在制作一款游戏来自学更多。

我想听听您关于存储/访问大量变量的一些想法。

到目前为止,我所做的是尝试将我的“关键”变量粘贴到单独的命名空间中,以便我可以在整个程序中访问它们。

这是一个好主意吗?我有一种强烈的感觉,它可能会回来咬我。

提前感谢=]

编辑:我是第一年的计算机专业学生,但我有几年的 Java 经验。C++ 是如此不同 =/

4

2 回答 2

1

将变量分组到结构或类中。如果您需要在类之外公开大量变量,那么您必须重新考虑您的设计

于 2012-11-02T13:52:45.037 回答
1

组织数据的主要武器是类:类是代表程序元素的对象。你命名它,给它变量和函数,然后在你的程序中创建它的实例。该类负责其所有数据,并可以防止其他类访问它。

class foo
{
    public:
    int iAmAPublicVariable; // <---This variable can be accessed by anyone who has access to an instance of the class

    private:
    int iAmAPrivateVariable; // <---- This variable can be accessed only from within the class itself.
};

控制对类数据的访问的一种好方法是使用 Getter 和 Setter。所以...

class foo
{
    public:
    int getImportantData();
    void setImportantData(int );

    private:
    int importantData;
};

int foo::getImportantData()
{
    //here I could put some validation to make sure that it's ok to give out importantData;
    return importantData; //this will return a copy of importantData, so the original is still safe within the class
}

void foo::setImportantData(int newData)
{
    //here I could put some validation to make sure that it's ok to overwrite importantData;
    importantData = newData;
}

使用这种设置,访问重要数据的唯一方法是通过 get 和 set 方法,因此该类可以最终控制发生在它身上的事情。

类应该是你程序的基础;如果您有大量变量,请查看它们的用途以及使用它们的函数,并尝试将过程分解为离散的功能区域。然后创建代表这些区域的类,并为它们提供所需的变量和方法。你的代码最终应该更小、更容易理解、更稳定、更容易调试、更可重用,并且更好地表示你试图建模的任何东西。

于 2012-11-02T14:27:30.563 回答