我有这个包含以下错误的C ++代码:
1. readBinaryFile
未在此范围内宣布
2. ret
未在此范围内声明
3. recursiveBinarySearch
未在此范围内声明。
有人可以帮我理解为什么会出现这些错误吗?
提前谢谢。
BinarySearch.h
#ifndef BINARYSEARCH_H
#define BINARYSEARCH_H
using namespace std;
class BinarySearch
{
public:
char readBinaryFile(char *fileName);
int recursiveBinarySearch(int start_index, int end_index, int targetValue);
};
#endif
BinarySearch.cpp
#include<iostream>
#include<fstream>
#include<cstdlib>
#include<vector>
using namespace std;
//vector to dynamically store large number of values...
vector<unsigned int> ret;
//variable to count the number of comparisions...
int n=0;
//method to read file....
void readBinaryFile(char* fileName)
{
ifstream read(fileName);
unsigned int current;
if(read!=NULL)
while (read>>current) {
ret.push_back(current);
}
}
//recursive binary search method
void recursiveBinarySearch(int start_index, int end_index, int targetValue)
{
int mid = (start_index+end_index)/2;
if(start_index>end_index)
{
cout<<n<<":-"<<endl;
return ;
}
if(ret.at(mid)==targetValue)
{
n++;
cout<<n<<":"<<mid<<endl;
return ;
}
else if(ret.at(mid)<targetValue)
{
n=n+2;//upto here two comparisions have been made..so adding two
start_index=mid+1;
return recursiveBinarySearch(start_index,end_index,targetValue) ;
}
else
{
n=n+2;
end_index=mid-1;
return recursiveBinarySearch(start_index,end_index,targetValue) ;
}
}
BinarySearch_test.cpp
#include "BinarySearch.h"
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char a[] ="dataarray.bin";
//assuming that all integers in file are already in sorted order
readBinaryFile(a);
int targetValue;
cout<<"Enter a Value to search:";
cin>>targetValue;
recursiveBinarySearch(0,ret.size()-1,targetValue) ;
return 0;
}
答案 0 :(得分:0)
在.cpp文件中,您错过了类名称来定义BinarySearch::
void BinarySearch::readBinaryFile(char* fileName)
{
//code here
}
并且如上所述,由于这些方法不是静态的,因此您需要一个对象来调用它们。
BinarySearch x;
x.readBinary(...);