c++ - 在对象向量上使用 std:sort 时出错
问题描述
我有一个 Person 对象指针向量。我正在尝试使用 std:sort 根据每个对象的“名称”对向量进行排序。尝试构建和运行时出现未解决的外部符号错误;谁能看到我哪里出错了?错误:
Error LNK2019 unresolved external symbol "public: static bool __cdecl Person::sortByName(class Person *,class Person *)" (?sortByName@Person@@SA_NPAV1@0@Z) referenced in function _main Lab1b C:\Users\jayjo\source\repos\Lab1b\Lab1b\Lab1b.obj 1
主要cpp:
#include <iostream>
#include "Person.h"
#include "Employee.h"
#include "Customer.h"
#include <vector>
#include <algorithm>
int main()
{
vector<Person*> people;
people.push_back(new Person("Peter"));
people.push_back(new Person("John"));
people.push_back(new Person("David"));
people.push_back(new Person("Aaron"));
sort(people.begin(), people.end(), Person::sortByName);
for (int i = 0; i < people.size(); i++)
{
cout << people[i]->getName() << endl;
}
}
人.h:
#pragma once
#ifndef Person_H
#define Person_H
using namespace std;
#include <iostream>
class Person
{
public:
Person(string);
virtual void printname();
static bool sortByName(Person* A, Person* B);
string getName();
protected:
string name;
};
#endif // !Person_H
个人.cpp:
#include "Person.h"
using namespace std;
Person::Person(string n)
{
name = n;
}
void Person::printname()
{
cout << "Name: " << name << endl;
}
string Person::getName()
{
return name;
}
static bool sortByName(Person* A, Person* B)
{
return (A->getName().compare(B->getName()));
}
解决方案
而不是这个:
static bool sortByName(Person* A, Person* B)
{
return (A->getName().compare(B->getName()));
}
这个:
bool Person::sortByName(Person* A, Person* B)
{
return (A->getName().compare(B->getName()) != 0);
}
在 C++ 中,您将类成员函数声明为static
,但static
在定义它时将关键字关闭。此外,该函数需要定义为类成员 ( Person::
)。
推荐阅读
- python - 访问一个类的对象以查看它是否存在于另一个类中
- javascript - 防止 history.replaceState 附加到 url
- c# - 为什么我的内存分配方法会抛出 Stack Overflow?
- c# - 简单的聊天应用程序在尝试托管 C#.NET 时崩溃
- c - 以正确的方式从 Object Dump 中获取 Shellcode
- shopify - 以集合为目标 - 液体
- c++ - 将 unordered_map 与 Catch2 谓词一起使用时类型不匹配
- javascript - 固定菜单不起作用(菜单不“粘”)
- javascript - 预检响应在 axios 中没有 HTTP ok 状态
- angular - Angular 6选择默认值不起作用