【发布时间】:2012-06-21 16:30:52
【问题描述】:
我只是在学习如何使用 C/C++,并正在尝试编写一个程序,其中“otherPerson”(名字、姓氏)继承自“person”(名字)。我被困在人的 compareTo 函数上。它应该按名字的字母顺序对指向人的指针数组进行排序。 (不确定我是否正确表达了这个想法)。最终目标是打印数组的排序内容。
我不断得到:
错误 LNK2019:函数 _main 中引用了无法解析的外部符号“void __cdecl compareTo(class person * * const,int)”(?compareTo@@YAXQAPAVperson@@H@Z) 1>c:\users\laur\documents\visual studio 2012\Projects\Project1\Debug\Project1.exe : 致命错误 LNK1120: 1 unresolved externals
当我尝试构建时。我在互联网上查看了更多信息,但我很确定我的包含语句是正确的。该函数旨在作为成员函数。
Test.cpp:
#include "stdio.h"
#include "otherPerson.h"
#include<iostream>
#include <string>
using namespace std;
void compareTo(person *array[7], int );
int main(){
int length = 7;
person* epicJourney[6];
//fill array
compareTo(epicJourney, length);
person.h:
#include <stdio.h>
#include <string>
using namespace std;
class person {
protected:
string firstName;
public:
person(string firstName);
virtual void setFirstName(string firstName);
virtual string getFirstName();
virtual void compareTo (person *array[7], int length);
virtual string toString();
};
person.cpp:
#include "person.h"
#include <string>
using namespace std;
person::person(string firstName){
this->firstName = firstName;
}
void person::setFirstName(string aName){
firstName =aName;
}
string person::getFirstName(){
return ((*this).firstName);
}
string person::toString(){
return (this->firstName);
}
void person::compareTo(person *array[], int length){
int i;
int j;
person *current;
for (i=1; i<length; i++){
current = array[i];
for (j=i; j>=1 && (current < array[j-1]); j--){
array[j] = array[j-1];
array[j-1] = current;
}
}
}
【问题讨论】:
-
你如何编译它们?也许你没有链接 Test.cpp 和 person.cpp
-
欢迎来到 Stack Overflow!这里当然欢迎新程序员提出问题,但您需要帮助我们一点。不幸的是,我不得不对这个问题投反对票,因为它包含一堵巨大的代码墙,其中大部分与问题无关。如果你能将你的问题减少到出现问题的代码的最低限度,我会改变我的投票。
-
作为奖励,通过将您的问题简化为最基本的问题,您可能会自己找到解决方案。如果您愿意,请随时在此处发布答案。
-
嗯,(重新)阅读 OPs 目标描述,我认为
person::compareTo()应该设计为仅与 person 类的另一个实例进行比较,::compareTo()应该重命名为::sortPersons()并接收来自person::compareTo()的实际实现(使用新的person::compareTo(const person& rhs)方法进行比较)。只是一些提示......