这是涉及的两个功能:
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]
错误的原因是什么?我没有看到代码中有任何错误。此外,我还有两个类似的函数(写),它工作得很好。
答案 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)
您通过const
和const
引用传递参数,但是,您调用的函数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是首选方法。