2013-03-16 30 views
2

我有一個類和方法有兩種:「沒有已知的隱式‘這個’參數轉換」錯誤

public: 
bool Search (const string & oName, const string & oAddr, 
        string & cName, string & cAddr) const 
    { 
     Company ctmp; 
     ctmp.own = oName + "|" + oAddr; 
     int place = searchDupl(ctmp,currentsize,0); 

     if (place < 0) 
      return false; 
     else 
     { 
      size_t pos = c[place].cmpn.find(' '); 
      cName = c[place].cmpn.substr(0,pos); 
      cAddr = c[place].cmpn.substr(pos+1); 
      return true; 
     } 
    } 

和在私人,我有searchDupl:

int searchDupl(Company cmp,int imax,int imin) 
    { 
     if (imax < imin) 
      return -1; 
     else 
     { 
      int mid = imin + ((imax - imin)/2); 

      if (c[mid].own > cmp.own) 
      { 
       return searchDupl(cmp,mid-1,imin); 
      } 
      else if (c[mid].own < cmp.own) 
      { 
       return searchDupl(cmp,imax,mid+1); 
      } 
      else 
      { 
       return mid; 
      } 
     } 
    } 

c是動態數組,這是在私人部分定義並在構造函數中初始化的。 currentize是int類型的變量(也是私有的,並在構造函數中初始化)定義了c中元素的數量。

當我嘗試使用G ++編譯它,顯示以下錯誤:

main.cpp: In member function ‘bool CCompanyIndex::Search(const string&, const string&, std::string&, std::string&) const’: 
main.cpp:69:54: error: no matching function for call to ‘CCompanyIndex::searchDupl(Company&, const int&, int) const’ 
main.cpp:69:54: note: candidate is: 
main.cpp:106:13: note: int CCompanyIndex::searchDupl(Company, int, int) <near match> 
main.cpp:106:13: note: no known conversion for implicit ‘this’ parameter from ‘const CCompanyIndex* const’ to ‘CCompanyIndex*’ 

我不知道什麼是錯的。

+1

'Search'是一個const方法,'searchDupl'不是。非const方法不能從const方法中調用。 – DCoder 2013-03-16 10:54:18

回答

7

你的第一種方法被聲明爲const -method

bool Search (const string & oName, 
       const string & oAddr, 
       string & cName, 
       string & cAddr) const 
//        ^^^^^ here 
{ 
    // ... 
} 

這意味着的this類型是const CCompanyIndex* const。當您嘗試從該方法中調用第二種方法時,該調用等效於this->searchDupl(ctmp,currentsize,0)。這就是爲什麼你的情況下this的類型是重要的。你需要的CCompanyIndex一個可變的情況下,即,你需要thisCCompanyIndex* const類型的,因爲第二個方法聲明爲

int searchDupl(Company cmp,int imax,int imin) 
//           ^^^ no const here 
{ 
    // ... 
} 

,因此你的代碼無法編譯。爲了解決這個問題,你應該聲明的第二個方法是const以及方法顯然是不改變類的狀態:

int searchDupl(Company cmp,int imax,int imin) const 
{ 
    // ... 
} 
+0

非常感謝。 – isklenar 2013-03-16 11:22:21

相關問題