C++编译器错误"no matching function"

C++ compiler error "no matching function"

本文关键字:matching function no C++ 错误 编译器      更新时间:2023-10-16

这是涉及到的两个函数:

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]

错误的原因是什么?我看不出代码有什么问题。此外,我还有另外两个类似的函数(write),它工作得很好。

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 ^^^

让我们看看错误消息:

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 qualified

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

这就是问题所在!

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

1)将rec更改为非const引用

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

选项#2是首选方法。

相关文章: