静态成员

时间:2013-12-25 17:49:00

标签: c++ oop static member

如何访问其他类的静态成员的成员?

像这样:

code.hpp:

class A
{
public:
    int* member;
    A();
};

class B
{
public:
    static A* StatOBJ;
};

code.cpp:

A* B::StatOBJ = new A();
int* B::StatOBJ->member = 42                //ERROR

我更喜欢在main()之外(或任何其他函数 - 就像静态变量一样定义),但我也在main()中尝试过。

A()给成员一些值(因此初始化它),我想改变它。

当我尝试编译时,我得到:

错误:' - >'之前的预期初始值设定项令牌

的行上

2 个答案:

答案 0 :(得分:3)

A::member未声明为static,因此在分配其值时不要再次指定其数据类型:

B::StatObJ->member = ...;

此外,A::member被声明为指针,因此您必须先分配它,然后才能为其赋值:

B::StatObJ->member = new int;
*(B::StatObJ->member) = 42;

或者:

B::StatObJ->member = new int(42);

无论哪种方式,通过给A构造函数来处理分配/赋值,可以更好地服务于这两者:

class A
{
public:
    int* member;
    A();
    ~A();
};

A::A()

    : member(new int(42))
{
}

A::~A()
{
    delete member;
}

A* B::StatObJ = new A();

或更好:

class A
{
public:
    int* member;
    A(int value);
    ~A();
};

A::A(int value)
    : member(new int(value))
{
}

A::~A()
{
    delete member;
}

A* B::StatObJ = new A(42);

答案 1 :(得分:0)

对您的代码进行一些小修改:

#include <iostream>

class A
{
    public: //needs to be public
     int* member;
};

class B
{
    public: // needs to be public
    static A* StatOBJ;
};
A* B::StatOBJ; //needs to be "defined" not just "declared"



int main(){
     B::StatOBJ = new A(); // you dont want to allocate more memory so drop the type
     B::StatOBJ->member = new int(42);   // unless you change A::member to int instead of (*int) this must be done  
}