Any unary expression is considered a cast expression.
The compiler treats cast-expression as type type-name after a type cast has been made. Casts can be used
to convert objects of any scalar type to or from any other scalar type. Explicit type casts are constrained by
the same rules that determine the effects of implicit conversions. Additional restraints on casts may result
from the actual sizes or representation of specific types.
// expre_CastOperator.cpp
The compiler treats cast-expression as type type-name after a type cast has been made. Casts can be used
to convert objects of any scalar type to or from any other scalar type. Explicit type casts are constrained by
the same rules that determine the effects of implicit conversions. Additional restraints on casts may result
from the actual sizes or representation of specific types.
// expre_CastOperator.cpp
// Demonstrate cast operator
#include <iostream>
using namespace std;
int main()
{
double x = 3.1;
int i;
cout << "x = " << x << endl;
i = (int)x; // assign i the integer part of x
cout << "i = " << i << endl;
}
// expre_CastOperator2.cpp
#include <iostream>
using namespace std;
class Casting{
public:
Casting(float x):m_int(5),
m_char('A'),m_float(&x)
{
}
operator float *(){
cout<<"Float cast *\n";
return m_float;
}
operator int(){
cout<<"int cast\n";
return m_int;
}
operator char(){
cout<<"Char cast\n";
return m_char;
}
private:
float *m_float;
int m_int;
char m_char;
};
int main()
{
int x;
float *y;
char z;
float temp = 9.4;
Casting *cast = new Casting(temp);
x=*cast;
y=*cast;
z=*cast;
cout<<x<<","<<*y<<","<<z<<"\n";
delete cast;
return 0;
}
Output:
No comments:
Post a Comment