尝试自学C ++。我正在尝试创建一个二进制搜索类,但是由于某种原因,我一直收到“未定义的引用”错误。当我尝试编译main.cpp时,出现以下错误。
/tmp/ccJwc0lu.o: In function `main':
main.cpp:(.text+0x11b): undefined reference to `binarySearch::binSearch(int*, int, int)'
collect2: error: ld returned 1 exit status
老实说,我不确定我在做什么错。我对C ++非常陌生,因此我一直在观看youtube视频在尽力创建自己的数据结构。
binarySearch.h
class binarySearch
{
private:
int first;
int last;
int position = -1;
bool so_far = false;
public:
int binSearch(int ra[], int size, int value);
};
binarySearch.cpp
#include "binarySearch.h"
int binarySearch::binSearch(int ra[], int size, int value) {
int mid = 0;
first = 0;
last = size-1;
while (first <= last && so_far != false) {
mid = first / last;
if (ra[mid] == value) {
so_far = true;
position = mid;
}
else if (value < ra[mid]) {
last = mid - 1;
}
else if (value > ra[mid]) {
first = mid + 1;
}
}
return position;
}
main.cpp
#include <iostream>
#include "binarySearch.h"
using namespace std;
int main() {
int SIZE = 5;
int ra[SIZE] = {1, 2, 3, 4, 5};
int results;
int value = 5;
binarySearch bsh;
results = bsh.binSearch(ra, SIZE, value);
cout << results << std::endl;
return 0;
}
如果在int数组中找到“值”,则仅显示索引位置的结果。