-2

请看下面的代码

游戏对象.h

#pragma once
class GameObject
{
public: 
    GameObject(int);
    ~GameObject(void);


    int id;

private:
    GameObject(void);


};

游戏对象.cpp

#include "GameObject.h"
#include <iostream>

using namespace std;

static int counter = 0;


GameObject::GameObject(void)
{
}

GameObject::GameObject(int i)
{
    counter++;
    id = i;
}


GameObject::~GameObject(void)
{
}

主文件

#include <iostream>
#include "GameObject.h"

using namespace std;

int main()
{
    //GameObject obj1;
    //cout << obj1.id << endl;

    GameObject obj2(45);
    cout << obj2.id << endl;;
//  cout << obj2.counter << endl;

    GameObject obj3(45);
    GameObject obj4(45);
    GameObject obj5(45);


    //Cannot get Static value here
    //cout << "Number of Objects: " << GameObject
    //

    system("pause");
    return 0;
}

在这里,我试图记录已经创建了多少个实例。我知道它可以由静态数据成员完成,但我无法使用 Main 方法访问它!请帮忙!

PS:

我正在寻求直接访问,没有 getter 方法

4

3 回答 3

2

您的静态变量counter无法访问,因为它不是GameObject. 如果要访问counter,则需要执行以下操作:

游戏对象.h

#pragma once

class GameObject
{
public: 
    ...
    static int GetCounter();
    ...
};

游戏对象.cpp

int GameObject::GetCounter()
{
    return counter;
}

然后你可以像这样访问变量:

cout << "Number of Objects: " << GameObject::GetCounter();

当然,还有其他访问静态变量的方法,例如使counter变量成为类的静态成员GameObject(我会推荐)。

于 2012-12-04T14:09:47.307 回答
0

在您的代码中,counter不是您的类的静态成员,而只是一个很好的旧全局变量。您可以在网上的任何地方阅读如何声明静态成员变量,但这里有一些片段:

游戏对象.h

#pragma once
class GameObject
{
public: 
    GameObject(void);
    GameObject(int);
    ~GameObject(void);

private:
    int id;

// static members
public: 
    static int counter; // <<<<<<<<<<< declaration
};

ameObject.cpp

#include "GameObject.h"

int GameObject::counter = 0; // <<<<<<<<<<< instantiation


GameObject::GameObject(void)
{
    counter++;
}

GameObject::GameObject(int i)
{
    counter++;
    id = i;
}


GameObject::~GameObject(void)
{
}

主文件

#include <iostream>
#include "GameObject.h"

using namespace std;

int main()
{
    GameObject obj2(45);
    cout << "version one: " << obj2.counter << endl;

    // second version:
    cout << "version two: " << GameObject::counter << endl;

    system("pause");
    return 0;
}

Afaik 在该类的实例上访问静态成员应该可以正常工作,但它给人的印象是错误的,您应该更喜欢版本二。

于 2012-12-04T14:23:59.370 回答
-1

没关系,我用getter方法做到了。关闭线程

于 2012-12-04T14:06:29.093 回答