Ambiguity while overloading the cast operator

血红的双手。 提交于 2019-12-11 04:48:47

问题


Consider the sample code below:

#include <iostream>

using namespace std;

class dummy
{
   private:
      int y;

   public:
      dummy(int b = 0) : y(b) {
      }

      friend ostream& operator<<(ostream& os, const dummy& obj);
};

ostream& operator<<(ostream& os, const dummy& obj)
{
   os << obj.y;
   return os;
}

class sample
{
   private:
      int x;

   public:
      sample(int a = 0) : x(a)
      {
      }

      operator dummy()
      {
         dummy d(100);
         return d;
      }

      operator int()
      {
         return x;
      }
};

int main()
{
   sample ob1(5);
   dummy d;

   //d = ob1; //Line1  
   d = (dummy)ob1; //Line2

   cout << d << "\n";
}

In Line1, an implicit cast is done. I understand how the implicit casting works in this case. The compiler gives no errors.

But in Line2, an explicit cast of sample object is done to dummy object. But the compiler gives the following error.

error: call of overloaded `dummy(sample&)' is ambiguous

note: candidates are: dummy::dummy(const dummy&)

note: dummy::dummy(int)

Questions:

  1. Why is these errors occurring?

  2. I do not understand the meaning of the error messages. Why the candidate functions of dummy class mentioned in the errors?


回答1:


The line:

d = (dummy)ob1

attempts to do the following:

  1. Construct a dummy object from obj1
  2. Assign that temporary dummy object to d

Part 1 is what causes the problems. To construct the temporary dummy object the compiler must search for some way to convert obj1 into a type which a dummy can be constructed from. It finds that there are two ways to do this:

  1. Call operator int
  2. Call operator dummy

You do not tell it which one of these two alternatives you want it to take, and so the code is ambiguous.


Your problem could be recreated (with the extraneous parts removed) as follows:

struct t_1 {};
struct t_2 {};
struct sample {
    operator t_1() const{ return t_1(); }
    operator t_2() const{ return t_2(); }
};
void f(t_1) {}
void f(t_2) {}
int main() {
    sample obj1;
    //overload resolution will fail
    //disambiguate with f(obj1.operator t_1()) or f(obj1.operator t_2())
    f(obj1);
}


来源:https://stackoverflow.com/questions/9476792/ambiguity-while-overloading-the-cast-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!