【发布时间】:2012-02-29 18:31:33
【问题描述】:
在以下情况下,sortMyVectors 的参数列表必须是什么样子,以及如何从 myFunction 中调用它?
std::vector<Vector2> myFunction ( MyObj * myObj ) {
std::vector<Vector2> myVectors;
// fill with lots of Vector2(double x, double y) objects
sortMyVectors( ???-myVectors, ???-myObj);
return myVectors;
}
void sortMyVectors( vector<Vector2> &myVectors, const MyObj &myObj) {
// sort the std::vector using myObj
// modifies order of Vector2s within the passed-in myVectors
// does not modify myObj
// need to be able to access with myVectors[0].x here...
}
调用方式是myFunction(&(*myObj));,其中myObj 是list<MyObj>::iterator。有没有更简洁的方法来写这个?
【问题讨论】:
-
没什么特别的:
sortMyVectors(myVectors, *myObj);myVectors是一个变量,所以可以直接传给引用;myObj是一个指针,所以需要解引用一次才能与MyObj&兼容。 -
感谢您的解释。但是,我收到此错误:“未定义对
sortMyVectors(std::vector<_Vector2, std::allocator<_Vector2> >&, MyObj&)的引用” -
您可以在文件中将
sortMyVectors移动到myFunction之前,或者在.c 或.h 文件的顶部为其添加前向声明:void sortMyVectors( vector<Vector2> &myVectors, const MyObj &myObj); -
哦...是的,这就是问题所在(我在课堂上遇到过,忘记输入
Classname::myFunction(...)。太好了,现在可以了:)你能不能看看我打电话给@的方式987654336@(我的问题的底部),让我知道如何让&(*)更干净一点? -
您可以更改为
myFunction(list<MyObj>::const_iterator& myObj),其他一切保持原样:它应该可以编译并运行,并且您可以直接传递您的迭代器。
标签: c++ pointers dereference