我一直在为大学班级的项目工作,该项目使用c ++中的类,不幸的是,每当我尝试调用在类中传递参数的函数时,程序均无法编译,并出现以下两个错误:
错误LNK2019无法解析的外部符号“ int __cdecl binsearch(class Course * * const,int,char * const)”(?binsearch @@ YAHQAPAVCourse @@ HQAD @ Z)在函数_main Project1 C:\ Users \ cvos \ source中引用\ repos \ Project1 \ Project1 \ courses_main.obj 1
和
错误LNK1120 1未解决的外部项目Project1 C:\ Users \ cvos \ source \ repos \ Project1 \ Debug \ Project1.exe 1
我已经查看了LNK问题,大多数结果表明,这与c ++ vs c中的符号有关(该修复无效),或者在Visual Studio中链接文件存在问题(该修复也没有),最后这与它有关,需要放在控制台子系统上(已经存在)。
奇怪的是,如果我注释掉对我在“ Course”类中通过参数传递的所有函数的调用,程序将正常运行。只有当我尝试使用在“ Course”类中创建的函数时,程序才能运行,导致我强烈怀疑我在将变量传递给成员函数的方式上做错了。
我将发布代码的相关部分:
在我的头文件“ courses.h”中,声明了我的功能:
int binsearch(Course* co_ptr[], int size, char search[]);
在第二个源文件“ courses_functions.cpp中,我定义了该函数:
int Course::binsearch(Course* co_ptr[], int size, char search[])
{
int low = 0, high = size - 1, first_index = -1, last_index = -1, num_of_entries = 0;
while (low <= high)
{
int mid = (low + high) / 2;
if (co_ptr[mid]->name == search)
{
bool found = false;
int i = mid;
while (!found) //Check values below mid
{
if (co_ptr[i]->name == search)
{
first_index = i; //first_index now holds a potential first occurence of our name
if (i == 0)
{
found = true;
}
}
else
{
found = true;
}
i--; //decrement i and check again.
}
i = mid; //Reset i
found = false; //Reset found
while (!found) //Check values above mid
{
if (co_ptr[i]->name == search)
{
last_index = i; //last_index now holds a potential last occurence of our name
if (i == size - 1)
{
found = true;
}
}
else
{
found = true;
}
i++; //increment i and check again.
}
break; //Breaks us out of the main while loop
}
else if (co_ptr[mid]->name < search)
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
if ((first_index != -1) && (last_index != -1))
{
for (int i = first_index; i <= last_index; i++)
{
std::cout << "\nEntry found: "
<< std::endl << co_ptr[i]->name << ' ' << co_ptr[i]->units << " units, grade:" << co_ptr[i]->grade;
num_of_entries++;
}
return num_of_entries;
}
else
{
std::cout << "\nEntry not found.";
return num_of_entries;
}
}
最后在我的主源文件“ courses_main.cpp”中,我调用该函数:
else if (selection == 3) //Display a course
{
char title[50] = "";
int results = 0;
std::cout << "\nEnter a class to search for: ";
std::cin.getline(title, 50, '\n');
std::cin.ignore();
results = binsearch(courses, size, title);
}
由于这是针对大学班级的,所以我不想使用任何其他方法,主要是想弄清楚为什么我使用的方法会返回我在上面共享的错误,但是我很乐意发布更多我的代码段(如果有必要)。
谢谢!
原因几乎可以肯定是以下原因之一:
binsearch()
,或以某种方式使用略有不同的签名(不太可能给出您告诉我们的内容)。需要查看您的“ courses.h”文件的声明。您可能已经在Course
类声明之外声明了binsearch。在这种情况下,您会收到如上所述的链接器错误。根据您在main ..中的用法,您无需在Course
类中实现此功能,它可以是Course类之外的独立功能。一旦将函数定义移到Course
类之外,只要您在MSVC IDE的同一项目中有Courses_functions.cpp和courses_main.cpp文件,链接器就会消失。