【问题标题】:Object value can not be changed对象值无法更改
【发布时间】:2016-08-18 13:30:07
【问题描述】:

我是一个新的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 进行调试时,它告诉我该对象已超出范围。我该如何解决... :-

【问题讨论】:

  • 如果你想从调用站点修改值,你需要通过引用传递。
  • @Peter Chen 显示最小可验证示例。
  • 不像在 Java 中,在 C++ 中的对象名称不是引擎盖下的引用。您正在将对象的副本传递给Globle_scoop_function(A a)(并且可能传递给setTest)。你需要了解C++ references并使用它们
  • "我是一个新的c++程序员,之前学过一些java。"你有很多东西要忘记。 C++ 不是 Java,这是一件好事。

标签: c++ oop variables object scope


【解决方案1】:

调用Globle_scoop_function(*this);*this深拷贝 复制到函数参数a。这是在Globle_scoop_function 末尾超出范围的那个 对象。对象*this 保持不变。

一种补救方法是将原型更改为void Globle_scoop_function(A&amp; a){。请注意&amp;,它表示引用。然后您修改main() 中的a 该引用。

代码中A 的所有各种实例都称为a 的事实只会增加混乱。

【讨论】:

  • 你为什么决定让 VC++ 来解决这个问题?
猜你喜欢
  • 2019-04-07
  • 1970-01-01
  • 1970-01-01
  • 2017-12-18
  • 2019-04-15
  • 1970-01-01
  • 2021-10-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多