C++ 为什么电话模棱两可

C++ Why the call is ambigous?

本文关键字:模棱两可 电话 为什么 C++      更新时间:2023-10-16
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); }
};

海湾合作委员会-墙 说:

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)

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

  • 调用 void* 函数需要向this添加 const qualifer
  • 调用 bool 函数需要将tovoid* 转换为 bool

因此,根据重载解析规则,两者都不是"更好"的匹配,并且调用被认为是不明确的。

也许你可以向第二个函数添加const;也许你可以从第一个函数中删除它(尽管我不想这样做(;也许你可以对thisto进行显式类型转换,以强制你喜欢的覆盖。

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

这意味着从tstfn调用它(这是非常量(将需要从myClass*const myClass*this的限定转换,因此调用这两个函数都需要对参数进行转换(this的处理方式与其他参数相同(,因此调用是不明确的。

仅仅因为你的testfn是一个非常量函数,它会调用get的非常量版本。非常量函数get,取boolconst void*。如果只有一个get函数(可能将void*作为第二个参数,而不管其恒定性如何(,那么将毫无歧义地调用。