c/c + + overloaded operator type conversion operator

Overloaded operator type conversion operator

Question: can I convert object a of type A to object B of type B??

Yes. This requires a conversion operator of type A

The following operator int()const{return val;} is the overloaded type Int type conversion operator

class Int{
public:
  Int(int i = 0) : val(i){}
  explicit operator int()const{return val;}
private:
  int val;
};

Note: if explicit type conversion operator is added, implicit conversion is not allowed. Explicit conversion is required, that is, the following form:

Int ii(10);
int i = (int)ii;

Without explicit, it is in the following form:

Int ii(10);
int i = ii;

Question: Class A defines a type conversion operator that can be converted to class B, and class B defines a constructor whose parameter is class A (that is, a conversion constructor. When you want to convert an object of class A to an object of class B, do you want to call the type conversion operator of class a or the constructor of class B??

In the following example, the constructor of class A is called

Example:

#include <iostream>

/*---------test1------------- */
class Int{
public:
  Int(int i = 0) : val(i){}
  explicit operator int()const{return val;}
private:
  int val;
};
/*---------test1------------- */

/*---------test2------------- */
struct A;
struct B{
  operator A()const;
  int val;
};

struct A{
  A(int i = 0) : val(i){}
  A(const B& b){
    std::cout << "A copy" << std::endl;
    val = b.val;
  }
private:
  int val;
};

B::operator A()const{
  std::cout << "B cast" << std::endl;
  return A(10);
}
  A f(const A&){}
/*---------test2------------- */
int main(){
/*---------test1------------- */
  Int i1;
  i1 = 10;
  int s = (int)i1 + 11;
  std::cout << s << std::endl;

  const Int i2(11);
  int s1 = (int)i2;
/*---------test1------------- */

/*---------test2------------- */
  B b1;
  A a1 = f(b1);//The compiler should not know who to call, but from the execution result, it calls the constructor of class A
  //A a1 = f(b1.operator A()); / / tells the compiler to call class B type conversion operator
  //A a1 = f(A(b1)); / / tells the compiler to call the constructor of class A
/*---------test2------------- */
}

github

QQ group of mutual learning in c/c + +: 877684253

My wechat: xiaoshitou5854

Tags: C++ github

Posted on Tue, 03 Dec 2019 14:28:34 -0800 by bokerfest