C ++编译器错误“无匹配功能”

时间:2013-04-03 03:30:42

标签: c++ compiler-errors

这是涉及的两个功能:

int FixedLengthRecordFile :: write (const int numRec, const FixedLengthFieldsRecord & rec)
{
    /*** some code ***/

    return rec.write(file); // FILE* file is an attribute of FixedLengthRecordFile
}


int FixedLengthFieldsRecord :: write (FILE* file) { /* ... code ... */ }

我收到了这个错误:

FixedLengthRecordFile.cpp: In member function ‘int FixedLengthRecordFile::write(int, const FixedLengthFieldsRecord&)’:
FixedLengthRecordFile.cpp:211:23: error: no matching function for call to ‘FixedLengthFieldsRecord::write(FILE*&) const’
FixedLengthRecordFile.cpp:211:23: note: candidate is:
FixedLengthFieldsRecord.h:35:7: note: int FixedLengthFieldsRecord::write(FILE*) <near match>
FixedLengthFieldsRecord.h:35:7: note:   no known conversion for implicit ‘this’ parameter from ‘const FixedLengthFieldsRecord*’ to ‘FixedLengthFieldsRecord*’
FixedLengthRecordFile.cpp:213:1: warning: control reaches end of non-void function [-Wreturn-type]

错误的原因是什么?我没有看到代码中有任何错误。此外,我还有两个类似的函数(写),它工作得很好。

2 个答案:

答案 0 :(得分:3)

int FixedLengthRecordFile::write( const int numRec, 
                                  const FixedLengthFieldsRecord& rec)
{
   /*** some code ***/

    return rec.write(file); // FILE* file is an attribute of FixedLengthRecordFile
}


int FixedLengthFieldsRecord::write(FILE* file) 

您通过constconst引用传递参数,但是,您调用的函数rec.write(file)不是const函数,它可以修改在对象中传递的函数,因此,编译器抱怨。

您应该执行以下操作:

   int FixedLengthFieldsRecord::write(FILE* file)  const  
       // add const both declaration and definition ^^^

答案 1 :(得分:0)

让我们看一下错误信息:

FixedLengthFieldsRecord.h:35:7:note: int FixedLengthFieldsRecord::write(FILE*)<near match>
FixedLengthFieldsRecord.h:35:7:note:   no known conversion for implicit ‘this’ parameter
    from ‘const FixedLengthFieldsRecord*’ to ‘FixedLengthFieldsRecord*’

它表示无法从const FixedLengthFieldsRecord*转换为FixedLengthFieldsRecord*

这是一个非常好的提示。

在以下行中,rec是const引用,

return rec.write(file); // FILE* file is an attribute of FixedLengthRecordFile

但以下功能是 NOT const限定

int FixedLengthFieldsRecord :: write (FILE* file) { /* ... code ... */ }

因此问题!

有(至少)两种解决方案:

1)将rec更改为非const参考

2)将write()方法的签名更改为const合格

选项#2是首选方法。