[英]C++ static null pointer
I can't figure out the following situation: I've 3 classes: 我无法弄清楚以下情况:我有3个课程:
AA.h 氨基酸
class AA
{
public:
AA();
static CC *i;
};
BB.h BB
class BB
{
public:
BB();
void static setI(CC *i);
};
CC.h 抄送
class CC
{
public:
CC();
};
AA.cpp 机密文件
AA::AA(){}
CC *AA::i= nullptr;
BB.cpp BB文件
BB::BB(){}
void BB::setI(CC *i)
{
i = new CC();
cout<<i<<endl;
cout<<AA::i;
}
CC.cpp 抄送
CC::CC(){}
So I've a static pointe of type CC in the class A. And i start the main in the following way: 因此,我在A类中具有CC类型的静态指针。并且我通过以下方式启动main:
int main(int argc, char *argv[])
{
BB::setI(AA::i);
return 0;
}
The output I get is 我得到的输出是
//0xaeed70
//0
So why AA::i
does not equal i
? 那么为什么
AA::i
不等于i
?
The parameter type of BB::setI
is CC *i
, the pointer itself is passed by value, i
is copied from the argument. BB::setI
的参数类型为CC *i
,指针本身通过值传递, i
从参数复制。 Any modification on i
inside the function has nothing to do with the original argument AA::i
. 函数内部对
i
任何修改都与原始参数AA::i
无关。
What you want might be pass-by-reference, ie 您想要的可能是引用传递,即
void BB::setI(CC *&i)
{
i = new CC();
cout<<i<<endl;
cout<<AA::i;
}
In the expression i = new CC()
variable i
is local variable of function BB::setI
which was initialized with the value of AA::i
because you called function like BB::setI(AA::i);
在表达式中,
i = new CC()
变量i
是函数BB::setI
局部变量,该函数已使用AA::i
的值初始化,因为您调用了类似BB::setI(AA::i);
函数BB::setI(AA::i);
. 。 Assigning any value to
i
will only change the value of this local variable, not the value of some other variable that has been used to initialize it when you called the function. 给
i
赋任何值将仅更改此局部变量的值,而不更改调用该函数时已用于对其进行初始化的某些其他变量的值。
It's exactly the same situation as this smaller example: 与这个较小的示例完全相同:
int i = 0;
void setI(int x)
{
x = 1234;
cout << x << endl;
cout << i;
}
int main()
{
setI(i);
}
As you can see more clearly here, you're assigning a new value to the function's parameter. 正如您在此处可以更清楚地看到的那样,您正在为函数的参数分配一个新值。
This parameter is unrelated to AA
's member. 此参数与
AA
的成员无关。
Regardless of its type, if you want a function to modify an object, you need to pass it a reference (or pointer) to that object; 不管其类型如何,如果您想让函数修改一个对象,都需要向其传递对该对象的引用(或指针)。 you can't pass the object's value.
您不能传递对象的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.