2017-05-15 99 views
-2

我有本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; 

    } 
+1

binarySearch.cpp不包含.h文件 – AndyG

+4

欢迎使用堆栈溢出!听起来像是你可以使用[好C++的书(http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – NathanOliver

+0

@AndyG我没有包括在这里的代码意外,但原来的代码有它。 –

回答

0

在您的.cpp文件,你错过的类名来定义BinarySearch::的功能

void BinarySearch::readBinaryFile(char* fileName) 
{ 
    //code here 
} 

和上面提到的,由于方法不是静态的,你需要一个对象来调用它们。

BinarySearch x; 
x.readBinary(...); 
+0

也许我应该阅读所有的评论 - 答案已经给出。为什么大多数人回答评论而不是“真实”的答案是有原因的,这样问题也可以被标记为回答! – florgeng