首页 > 解决方案 > 在对象向量上使用 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()));
}

标签: c++

解决方案


而不是这个:

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::)。


推荐阅读