【发布时间】:2020-06-10 15:31:12
【问题描述】:
例如,
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 的值,并且我想避免使用全局变量。有什么解决办法吗?
谢谢
【问题讨论】:
-
int depth = Obj.getDepth();有什么问题? -
定义“访问值”。哪些元素?所有两个向量?然后,您可以提供访问器来返回 const 引用或成员变量的副本。如果您想从一个函数中全部返回它们,那么只需返回包含所有感兴趣字段的
std::tuple或struct。或者从getDepth()返回它们,并以其他方式发出错误信号,例如通过抛出异常,而不是返回错误代码。 -
喜欢所有会员访问;
Obj.positionX和Obj.positionY。我认为您需要good book。 -
感谢您的回复。我想我错过了一些观点。我不确定我是否以正确的方式表达它。但是当我在 int main() 函数中使用 Obj.positionX 时,它不会访问 GetDepth_Class::getDepth() 内部的 positionX 输出,它只能访问类 GetDepth_Class 中定义的 positionX。我要做的就是使用 getDepth() 输出的 positionX 和 positionY 的值在 main() 中进行一些计算。谢谢。
-
你想从
getDepth()函数中获取这两个值并在main()中访问它吗?