简体   繁体   中英

C++ Why the call is ambigous?

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); }
};

gcc -Wall says:

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)

Both function calls require a type conversion:

  • calling the void* function requires adding a const qualifer to this
  • calling the bool function requires converting to from void* to bool .

So, by the overload resolution rules, neither is a "better" match than the other, and the call is considered ambiguous.

Perhaps you can add const to the second function; perhaps you could remove it from the first (although I'd prefer not to); perhaps you can do an explicit type conversion of either this or to to force your preferred override.

Because void *get(long i, void* const to) is const .

This means that calling it from tstfn (which is non-const) would require qualification conversion for this from myClass* to const myClass* , so calling both functions would require a conversion for the arguments ( this is treated in the same way as other arguments), so the call is ambiguous.

Simply because your testfn is a non-const function, which would call the non-const version of get . The non-const function get , takes bool not const void* . Had only one get function was there (possibly taking void* as the second argument, irrespective of its constness), then would be called without ambiguity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM