首页 > 解决方案 > 如何在 C++ 中访问范围的变量输出?

问题描述

例如,

class GetDepth_Class {
    public:
        vector<int> positionX, positionY;
        vector<int>::iterator it;
        int getDepth();
    };

int GetDepth_Class::getDepth(){
                ......
                ......
                if (scalar[0] == 0 && scalar[1] == 0 && scalar[2] == 0) {

                    it = positionX.begin();
                    positionX.insert(it, i + 80);

                    it = positionY.begin();
                    positionY.insert(it, j + 80);
                }

                for (int i = 0; i < positionX.size(); i++) {
                    cout << positionX[i] << "," << positionY[i] << endl;
                }


return EXIT_SUCCESS;//realsense depth camera module
}

    int main() {

    GetDepth_Class Obj;
    Obj.getDepth();

    //Here I would like to access the values of vector positionX and vector positionY output from GetDepth_Class::getDepth(), 
    //how should I do if I want to avoid using global variable?

}

我想从 main() 中的 getDepth() 访问向量 positionX 和向量 positionY 输出的值,并且我想避免使用全局变量。有什么解决办法吗?

谢谢

标签: c++scope

解决方案


由于您已将所有类成员声明为公共,因此您可以直接通过Obj.positionXetc 访问它们。这不是很好的做法,但给出的示例代码是最简单的方法。


推荐阅读