gpt4 book ai didi

c++ - 对象值不能改变

转载 作者:行者123 更新时间:2023-11-28 05:32:53 25 4
gpt4 key购买 nike

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

最佳答案

调用 Globle_scoop_function(*this);*this深度复制到函数参数 a . 那个对象在 Globle_scoop_function 结束时超出了范围。对象 *this 保持不变。

一种补救措施是将原型(prototype)更改为 void Globle_scoop_function(A& a){。请注意 & 表示一个引用。然后,您通过该引用修改 main() 中的 a

您的代码中 A 的所有实例都称为 a 的事实只会增加困惑。

关于c++ - 对象值不能改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39019532/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com