如何在C++中访问作用域的变量输出?
How do I access variables output of a scope in 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((中矢量位置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()
相关文章:
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- 使用静态变量的递归调用的不同输出
- C++具有模板成员变量的类. 和参数内存输出
- 更改输出的变量
- 如何在C++中访问作用域的变量输出?
- 简化C++包括变量名称和函数输出的模式
- C++ - 输出与初始化变量不同?
- 是否可以在C++中基于程序集输出(.dll或.exe)定义变量
- 当对字符变量使用toupper()时,所述char变量输出多个字符.我该如何防止这种情况发生
- 如何让变量随机输出四个单词之一
- 输出(用于 GraphViz)提升图顶点及其属性,使用具有私有变量的类作为捆绑属性
- 如何将C++输出捕获到 Bash 变量?
- 当我在循环内打印变量时无限输出
- 字符串比较在与变量一起使用时给出不同的输出
- 双变量输出 32767 始终代替用户输入
- 使用std :: ofstream中的c 中的float变量输出
- C++:Xcode中未初始化的变量输出为0
- C++转义字符和引用变量输出混淆
- 矢量类C++的变量输出不正确
- 硬编码变量输出中没有反斜杠,但在文件输出中存在