c++ - 类内部的全局变量和局部函数变量

标签 c++

我尝试了一个 C++ 程序,我在类中声明了一个名为“a”的 int 类型变量。并创建了一个名为“b”的函数,我在其中再次声明了一个名为“a”的变量并为其赋值。函数内的变量“a”被认为是局部变量。如果我想将值赋给类定义中(而不是函数内部)中的变量 a,我该怎么做?

#include <iostream>

using namespace std;

class a{
    public:int a;//need to assign value for this "a" inside the function how can i do it
    int b(){
        int a=5;
        a=7;
        cout<<a;
    }
};
int main() {
    a A;
    A.b();
}

最佳答案

要访问类变量,您可以使用 this 关键字。 有关“this”关键字的更多解释和知识,您可以前往 here

#include <iostream>

using namespace std;

class a{
    public:int a;//need to assign value for this "a" inside the function how can i do it
    int b(){
        int a=5;
        a=7;
        this->a = 8; // set outer a =8
        cout<< "local variable a: " << a << endl;
        cout<< "class a object variable a: " << this->a << endl;
        return 0;
    }
};
int main() {
    a A;
    A.b();
    cout << "A's variable a: " << A.a << endl; //should print 8
    return 0;
}

关于c++ - 类内部的全局变量和局部函数变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48724551/

相关文章:

c++ - 将数学表达式传递给函数

c++ - 为什么我不能分配具有已删除或私有(private)析构函数的类的数组?

c++ - 在 Qt 中将结构传递给信号

c++ - 什么是独立于操作系统的方式来打开 C++ 中关联程序的文件?

c++ - Android NDK OpenGLES 不渲染三角形

C++ 模板 : cannot call my function from main. cpp

c++ - 英特尔 C++ 编译器 : What is highest GCC version compatibility?

c++ - 函数参数的隐式实例化

c++ - 在 cv::resize() 之后图像奇怪地改变了

c++ - C++ 可以通过添加一些东西而不删除所有以前的上下文来处理记事本输入文件吗?