Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/141.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 静态成员的成员_C++_Oop_Static_Member - Fatal编程技术网

C++ 静态成员的成员

C++ 静态成员的成员,c++,oop,static,member,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()之外(或任何其他函数——就像定义静态变量一样)使

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

像这样:

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()为成员添加了一些值(并对其进行初始化),我想对其进行更改

当我尝试编译此文件时,我得到:

错误:在“->”标记之前需要初始值设定项


在带有//ERROR

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

B::StatObJ->member = ...;
另外,
A::member
被声明为指针,因此必须先分配它,然后才能为其赋值:

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

无论哪种方式,通过给
A
一个构造函数来处理分配/赋值,这两种方法都会更好:

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

或者更好:

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


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

#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  
}
#包括
甲级
{
公共服务必须是公共的
国际*成员;
};
B类
{
公共服务必须是公共的
静态A*StatOBJ;
};
A*B::斯塔托布吉//需要“定义”而不仅仅是“声明”
int main(){
B::StatOBJ=new A();//您不想分配更多内存,所以请删除该类型
B::StatOBJ->member=newint(42);//除非将A::member更改为int而不是(*int),否则必须执行此操作
}

“成员”默认范围为私有。所以你不能访问它。试试疯狂的东西:
A*B::StatObj=(B::StatObj=newa,B::StatObj->member=42,B::StatObj)对不起,忘了在那里放公用电话
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);
#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  
}