C++:从函数更改类成员值

标签 c++ class oop scope

对于发布这样一个基本问题,我深表歉意,但是对于为什么这不起作用以及如何让它起作用,我找不到合适的答案。

我在这里简化了我的问题:

#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/

相关文章:

c++ - 反斜杠和引号不计入字符串长度?

c++ - 指针拷贝的虚拟方法不起作用

C++ - 为什么可以在复制构造函数中直接访问传递的对象的私有(private)变量?

oop - 增删改查的意义

c++ - 可以为了速度牺牲常量正确性吗?

c++ - 找到cmd.exe文件的位置

c++ - 特征类中的成员函数 "name"? (通用适配器)

python - 如何使用 Python、pybind11 和 Mingw-w64 构建 setup.py 来编译 C++ 扩展?

python - 使用 python 类的元胞自动机

oop - 你能用 vbscript 和 ASP 上课吗?