在类管理器中我有这些方法:
void Manager::SortElementsById()
{
sort(world->GetElements().begin(), world->GetElements().end(), compareById);
}
bool compareById(const Element* element1, const Element* element2)
{
return element1->Id < element2->Id;
}
world 是指向 World 类对象的指针。类世界包含:
vector<Element*> elements;
vector<Element*> World::GetElementss()
{
return this->elements;
}
类元素包含:
int Id;
我有两个问题:
为什么它不起作用?我有以下错误:“错误 C2065 'compareById':未声明的标识符”
最终,我希望将 Id(在 Element 类中)设为私有(private),并通过公共(public)方法 GetId() 返回这些字段的值。当我想在 const 对象上执行此方法时,这是非法的,所以我不知道在这些条件下我能做些什么来对这些 vector 进行排序。
最佳答案
I have following error: "Error C2065 'compareById': undeclared identifier"
像往常一样,compareById
必须在使用前声明。 (除非它和类内函数是同一个类的成员,但它似乎根本不是类成员。)
It is illigal when i want to execute this method on const object
听起来你只需要让你的函数成为一个 const 成员函数。像这样声明
int GetId() const;
你将被允许在 const
对象上调用它。
关于c++ - 根据这些对象的属性值对指向对象的指针 vector 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43483745/