C++为什么呼叫是暧昧的?

Вла*_*чёв 15 c++

class myClass {
   int arr[100];
public:
    void *get(long i, void* const to) const;
    void *get(long i, bool nog);
    void *tstfn(void* const to) { return get(0L,to); }
};
Run Code Online (Sandbox Code Playgroud)

gcc -Wall说:

dt.cpp: In member function ‘void* myClass::tstfn(void*)’:
dt.cpp:6:49: warning: ISO C++ says that these are ambiguous, even though the worst conversion for the first is better than the worst conversion for the second: [enabled by default]
dt.cpp:4:9: note: candidate 1: void* myClass::get(long int, void*) const
dt.cpp:5:9: note: candidate 2: void* myClass::get(long int, bool)
Run Code Online (Sandbox Code Playgroud)

Mik*_*our 27

两个函数调用都需要类型转换:

  • 调用该void*函数需要添加一个constqualiferthis
  • 调用bool函数需要转换tovoid*bool.

因此,通过重载决策规则,两者都不是"更好"的匹配,并且该调用被认为是不明确的.

也许你可以添加const第二个功能; 也许你可以从第一个中删除它(虽然我不愿意); 也许您可以对其中一个进行显式类型转换thisto强制使用首选覆盖.


Ant*_*vin 13

因为void *get(long i, void* const to)const.

这意味着从tstfn(它是非const)调用它将需要thismyClass*to的限定转换const myClass*,因此调用这两个函数将需要转换参数(this以与其他参数相同的方式处理),因此调用是不明确的.


Aja*_*jay 6

只是因为你testfn是一个非const函数,它将调用非const版本get.非const函数get,bool不需要const void*.只有一个get函数存在(可能void*作为第二个参数,不管它的常量),然后将被称为没有歧义.