0
#include "B.h"

class A
{
    public :
        A()
        {
            s_b = new B();
            b = new B();
        }

       static B *s_b;

        B *b;
};



#include<iostream>

using namespace std;

#include "A.h"

int main()
{
    cout<<"hello";
}

在我的项目中,我看到了上面的静态对象。但无法知道它的确切用途以及它们与一般对象有何不同。请帮助我找出我可以用 s_b 做什么,而 b 没有这样做。

4

3 回答 3

3

一方面,s_b不会为每个创建的实例占用内存A,而b确实如此。sizeof(A)增加,b但不增加s_b

Astatic在类的所有实例之间共享,因此它的作用类似于全局。你不需要一个对象来访问它,你可以A::s_b直接使用。

于 2012-12-13T14:23:31.780 回答
2

静态成员和在命名空间范围内定义的对象或函数之间唯一真正的区别是访问。例如,静态数据成员可以是私有的,在这种情况下,它不能在类之外访问;静态函数成员可以访问私有数据成员,而命名空间范围内的函数则不能。

访问语法也不同:如果在类之外,您必须使用ClassName::memberName(或classInstance.memberName)访问成员。没有using其他方法可以使其可访问。

于 2012-12-13T14:26:08.467 回答
1

generally speaking static members have to be initialized outside the declaration of the class except for constant int type if you are not using C++11.

So your code posted above is flawed. you need a statement like

    A::s_b = B();

outside the class A { ... }; To initialize an static member inside an non static constructor is wrong because the constructor is used to construct an object but the static member does not belong to the object but belong to the class. So these static members can not be modified through static member functions.

Think "class" as "human being" and an object of that "class" as a specific person, like "John Smith". So if you have a field, "salary". That should be a non-static field since each person has a different salary. But if you have field, "total_population", which should be a static member because this field semantically does not belong to one specific person but to the whole "human being".

于 2012-12-13T14:42:22.367 回答