2013-04-03 97 views
1

这些都是涉及到的两个功能:C++编译器错误“不匹配功能”

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

而且请在课堂上展示功能的声明。 –

+2

在执行'FixedLengthRecordFile :: write'之前,你有'FixedLengthFieldsRecord :: write'原型吗? – Kupto

回答

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

但是,考虑到'write'的函数名称,我想知道这是否会起作用,因为调用的对象'write'将被视为const。 – user1167662

+1

@ user1167662是真的,所以OP必须保证它不会修改对象或不会通过const或const ref传递。 – taocp

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

它说,它无法做到FixedLengthFieldsRecord*

const FixedLengthFieldsRecord*转换这是一个很不错的提示。

在下面一行,rec是const引用,

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

但下面的函数是const合格

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

因此,问题!

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

1)改变rec到非const参考

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

选项# 2是首选的方法。

+0

假设'write'函数不需要修改'rec'(考虑名字,这似乎不太可能) – user1167662

+0

我明白了。这就是我说明两种方法的原因。选项#2是首选,但如果不适用。选项#1仍然存在。 – Arun