简体   繁体   中英

Why is member function call “ambiguous”?

Why is my overloaded member function only "ambiguous" as a char and not an int and string?

I'm trying to create a one-code path for my Char class by funneling code through an overloaded equals() function. It works fine when I use equals as an int and string but is ambiguous as a char.

class Char
{
private:
    char cData;
    int iData;
    string sData;
public:
    //Mutators:
    void equals(char c);
    void equals(int c);
    void equals(string c);

    //Constructors:
    Char(char c);
    Char(int c);
    Char(string c);
};

void Char::equals(char c)
{
    cData = c;
}

void Char::equals(int c)
{
    iData = c;
}

void Char::equals(string c)
{
    sData = c;
}

Char::Char(char c)
{
    this->equals(c); //Call to member function 'equals' is ambiguous
}

Char::Char(int c)
{
    this->equals(c);
}

Char::Char(string c)
{
    this->equals(c);
}

The error only happens for char, which is confusing since string works fine. I expected it to work for all of them since that's been the case so far.

you can use a single equal method to accept a char or an int . like

void euqals(unsigned int c_i);

It's ambiguous because if you do

Char c(42);

The compiler does not know whether it should call the char or int constructor. Both are an equally good match.

The same goes for equals(123); . Again, both the char and int overloads match and the compiler cannot tell which one you intend to call.

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