这个错误信息是什么意思?
error: 调用重载‘setval(int)’不明确巨大的.cpp:18:注意:候选人是:无效巨大::setval(无符号整数)巨大的.cpp:28:注意:无效巨大::setval(常量字符*)
我的代码如下:
#include #define 字节 8使用命名空间 std ;类巨大{私人的:无符号字符数据[字节];上市:void setval(unsigned int);void setval(const char *);};无效巨大:: setval(无符号整数t){for(int i = 0; i
字面量 0
在 C++ 中有两种含义.
一方面,它是一个值为 0 的整数.
另一方面,它是一个空指针常量.
由于您的 setval
函数可以接受 int
或 char*
,因此编译器无法确定您指的是哪种重载.>
最简单的解决方案是将 0
强制转换为正确的类型.
另一种选择是确保首选 int
重载,例如通过将另一个作为模板:
类巨大{私人的:无符号字符数据[字节];上市:void setval(unsigned int);模板void setval(const T *);//未实现模板 <>void setval(const char*);};
What does this error message mean?
error: call of overloaded ‘setval(int)’ is ambiguous
huge.cpp:18: note: candidates are: void huge::setval(unsigned int)
huge.cpp:28: note: void huge::setval(const char*)
My code looks like this:
#include <iostream>
#define BYTES 8
using namespace std ;
class huge {
private:
unsigned char data[BYTES];
public:
void setval(unsigned int);
void setval(const char *);
};
void huge::setval(unsigned int t) {
for(int i = 0; i< BYTES ; i++) {
data[i] = t;
t = t >> 1;
}
}
void huge::setval(const char *s) {
for(int i = 0; i< BYTES ; i++)
data[i] = s[i];
}
int main() {
huge p;
p.setval(0);
return 0;
}
The literal 0
has two meanings in C++.
On the one hand, it is an integer with the value 0.
On the other hand, it is a null-pointer constant.
As your setval
function can accept either an int
or a char*
, the compiler can not decide which overload you meant.
The easiest solution is to just cast the 0
to the right type.
Another option is to ensure the int
overload is preferred, for example by making the other one a template:
class huge
{
private:
unsigned char data[BYTES];
public:
void setval(unsigned int);
template <class T> void setval(const T *); // not implemented
template <> void setval(const char*);
};
这篇关于重载函数的调用不明确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!