Cast operator and operator casts

Cast operator

	char b = 'a';
	cout << (int)b << endl;

Casts operator

In C ++, the name of the type (including the name and the like) itself is also an operator, i.e. type casting operator.

Type casting operator is unary operator, it may be overloaded, but only overloaded member function, as global functions can not be overloaded. After appropriate overloading, (type name) of the target object is cast expression is equivalent to the object type name .operator (), i.e., becomes a function call to the operator.

The following procedure for the double type casting operator is overloaded.

#include <iostream>
using namespace std;
class Complex
{
	double real, imag;
public:
	Complex(double r = 0, double i = 0) :real(r), imag(i) {};
	operator double() { return real; }  //重载强制类型转换运算符 double
};
int main()
{
	Complex c(1.2, 3.4);
	cout << (double)c << endl;  //输出 1.2
	double n = 2 + c;  //等价于 double n = 2 + c. operator double()
	cout << n;  //输出 3.2
	return 0;
}

The output of the program is:
1.2
3.2

S 8 double line operator is overloaded. When overloaded cast operator need not specify the type of the return value, because the return value type is determined, the type of the operator itself is represented, this is the double.

Overload effect after that the first row 13 (double) c is equivalent to c.operator double ().

With heavy load of double operator, where the emergence of double this type of variable or constant, an object of type Complex If it does, then the operator double member function of the object is invoked, then take the return value use.

For example, line 14, the Bank of c compiler that this location if there is a double data type, can be explained through, but just Complex class overloads the operator double, so the Bank is equivalent to:

double n = 2 + c.operator double();

The following code is also used type cast:

int x;
 while(cin>>x){..
 }
 return 0; 

Overloading the cin bool type determination program while () should occur bool type, so cin >> x is cast to bool.

Published 52 original articles · won praise 0 · Views 680

Guess you like

Origin blog.csdn.net/UniversityGrass/article/details/104687462