c++: cast operator vs. assign operator vs. conversion constructor priority

北城余情 提交于 2019-12-05 03:31:15

The statement t1 = t2; is equivalent to:

t1.operator=(t2);

Now the usual rules of overload resolution apply. If there's a direct match, that's the chosen one. If not, then implicit conversions are considered for use with the (automatically generated, "implicitly defined") copy-assignment operator.

There are two possible implicit, user-defined conversions. All user-defined conversions count equal, and if both are defined, the overload is ambiguous:

  • Convert t2 to a Test1 via the Test1::Test1(Test2 const &) conversion constructor.

  • Convert t2 to a Test1 via the Test2::operator Test1() const cast operator.

when I use following code than priority is given first to the constructor rather than cast operator

 #include<iostream>
 using namespace std;
 class C1;
 class C2
 {
      int x;
 public:
     operator C2()
     {
       C2 temp;
       cout<<"operator function called"<<endl;
       return temp;
    }
 };
class C1
{
   int x;
public:
   C1():x(10){}
   C1(C2)
  {
    cout<<"constructor called"<<endl;
  }
};
 int main()
{
  C1 obj1;
  C2 obj2;
  obj1=obj2;
}

Output Constructor called

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