gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:01:37 25 4
gpt4 key购买 nike

例如,

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()输出的vector positionX和vector positionY的值,并且我想避免使用全局变量。有什么解决方案吗?

谢谢

最佳答案

您也可以使用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()读取了它。

Sample Output:


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

关于c++ - 如何在C++中访问作用域的变量输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62307357/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com