我是一名新的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的事实只会加剧混乱。

10-07 19:02
查看更多