1

クラスと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は動的配列であり、プライベートセクションで定義され、コンストラクターで初期化されます。currentsizeは、cの要素の量を定義するint型の変数です(これもprivateで、コンストラクターで初期化されます)。

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*’

何が悪いのかわかりません。

4

1 に答える 1

7

最初のメソッドはconst-methodとして宣言されています

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

これは、のタイプthisが。であることを意味しconst CCompanyIndex* constます。そのメソッド内から2番目のメソッドを呼び出そうとすると、その呼び出しはと同等this->searchDupl(ctmp,currentsize,0)です。これがthis、あなたの場合のタイプが重要である理由です。の可変インスタンスが必要ですCCompanyIndex。つまり、2番目のメソッドは次のように宣言されているため、this型である必要があります。CCompanyIndex* const

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

したがって、コードのコンパイルに失敗します。これを修正するには、2番目のメソッドを宣言する必要があります。constまた、メソッドは明らかにクラスの状態を変更していません。

int searchDupl(Company cmp,int imax,int imin) const
{
  // ...
}
于 2013-03-16T11:15:20.283 に答える