如何在C++中访问作用域的变量输出?

How do I access variables output of a scope in C++?

本文关键字:变量 输出 作用域 访问 C++      更新时间:2023-10-16

例如,

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((中矢量位置X和矢量位置Y输出的值,并且我想避免使用全局变量。有什么解决方案吗?

谢谢

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

您也可以使用struct返回多个值:

#include <iostream>
#include <vector>
using namespace std;
// using a struct for returning multiple variables
struct Decl
{
vector<int> posX;
vector<int> posY;
};
class GetDepth_Class
{
// these are private members now
vector<int> positionX, positionY;
vector<int>::iterator it;
public:
Decl getDepth();
};
Decl GetDepth_Class::getDepth()
{
Decl d;
it = positionX.begin();
positionX.insert(it, 80);
it = positionY.begin();
positionY.insert(it, 74);
d = {positionX, positionY};
for (int i = 0; i < positionX.size(); i++)
cout << positionX[i] << "," << positionY[i] << endl;
return d;
}
int main()
{
GetDepth_Class Obj;
Decl x = Obj.getDepth();
for (int i = 0; i < x.posX.size(); i++)
cout << x.posX[i] << ' ';
cout << endl;
for (int i = 0; i < x.posY.size(); i++)
cout << x.posY[i] << endl;
return 0;
}

我知道这有点混乱,但可以理解。

我已经设置了{positionX, positionY}并返回并使用循环main()读取它。

示例输出:

80,74 // printed from class function
80    // positionX from main()
74    // positionY from main()