【发布时间】:2013-08-13 01:30:38
【问题描述】:
我被这段代码卡住了:
class MyObject
{
public:
int value;
}
class MyClass
{
private:
btAlignedObjectArray<MyObject*> m_objects;
public:
int comp (MyObject *a, MyObject *b)
{
return calculateTheNewValue(a->value) < calculateTheNewValue(b->value);
}
void doSort()
{
m_objects.quickSort(comp);
}
//edit: this member function is needed to do the sorting
int calculateTheNewValue(int v)
{
// do some calculation using other members variables, not necessarily m_objects
}
};
它无法编译,因为 comp 是一个非静态成员函数。
comp 不能是静态的,因为它需要访问成员变量 m_objects。
另外,它会破坏 m_objects 的封装以拥有一个静态函数并像这样调用它
MyClass::doSort(myClass.m_objects)
编辑
这是btAlignedObjectArray的声明
http://bulletphysics.org/Bullet/BulletFull/btAlignedObjectArray_8h_source.html
第 365 行有声明或quicksort
【问题讨论】:
-
comp 不需要对 m_objects 进行任何访问,因为您已经传递了应该相互比较的对象。您确定示例完整吗?
-
@j_schultz 抱歉,我遗漏了代码的重要部分,可能是咖啡太多(或太少)。 calculateTheNewValue() 是进行排序所需的成员函数
-
显示
btAlignedObjectArray::quickSort的声明。 -
如果 calculateTheNewValue 不引用 m_objects,comp 和 calculateTheNewValue 可以是静态的。
-
@lulyon calculateTheNewValue 计算引用其他成员变量的值,我必须进行编辑以澄清
标签: c++ sorting vector std member-functions