我是一名新的C ++程序员,之前已经学习过一些Java。我正在做我的任务。而且我只是无法听到有关此问题的消息。
class A{
private:
bool test;
public:
void anotherSetTest();
void setTest();
A();
};
void Globle_scope_function(A a){
a.setTest(true);
}
A::A(){
test = false;
}
void A::setTest(bool foo){
test = foo;
}
void A::anotherSetTest(){
Globle_scope_function(*this);
}
int main(){
A a;
a.anotherSetTest();
cout<<a.getTest()<<endl;//It suppose to output true, but why does it output false.
system("pause");
return 0;
}
当我使用Visual Studio进行调试时,它告诉我对象已超出范围。我该怎么解决...:-
最佳答案
调用Globle_scoop_function(*this);
将*this
的深层副本复制到函数参数a
。该对象在Globle_scoop_function
的末尾超出范围。对象*this
保持不变。
一种补救方法是将原型更改为void Globle_scoop_function(A& a){
。注意&
,它表示参考。然后,您可以通过该引用在a
中修改main()
。
您代码中A
的所有各种实例都称为a
的事实只会加剧混乱。