对于发布这样一个基本问题,我深表歉意,但是对于为什么这不起作用以及如何让它起作用,我找不到合适的答案。
我在这里简化了我的问题:
#include <iostream>
using namespace std;
class A {
public:
int x;
};
void otherFunction() {
A A;
cout<<"X: "<<A.x<<endl;
}
int main(){
A A;
A.x = 5;
otherFunction();
return 0;
}
构造后类成员是否变为常量?
如何扩大对类所做的更改的范围?
结构体有这样的限制吗?
预先感谢您的回答。
最佳答案
您没有得到预期的输出,因为在 otherFunction()
中您正在创建一个类型 A 的新对象,您之前没有为其赋值!
继续阅读 scope of a variable在 C++ 中学习更多
尝试运行下面给出的代码,您应该得到输出 5。
#include <iostream>
using namespace std;
class A {
public:
int x;
};
void otherFunction(A a) {
cout << "X: " << a.x << endl;
}
int main(){
A a;
a.x = 5;
otherFunction(a);
return 0;
}
或者你可以这样做,这在 OOP 中被认为是一种很好的做法
class A{
private:
int x;
public:
void update(int newx){
x = newx;
}
int getX(){
return x;
}
};
int main(){
A a;
a.update(5);
cout << a.getX() << endl;
return 0;
}
关于C++:从函数更改类成员值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36257202/