例如:将一个double类型的数据强制转化为整形
#include<iostream>
using namespace std;
int main()
{
double a = 1.44;
int b = int(a);
cout << b<<endl;//输出:1
}
下面我们来实现对一个类中的对象进行强制转化:
#include<iostream>
using namespace std;
class Student
{
public:
double m_age;
//无参构造函数
Student()
{
m_age = 20.4;
}
//打印
void print()
{
cout << m_age << endl;
}
};
int main()
{
Student a;
a.print();
cout << int(a) << endl;//报错
return 0;
}
我们可以知道上面的代码报错了,由此可知我们不能直接对对象类型的数据进行强制转化
因此要进行转化就得使用运算符重载的方法:
#include<iostream>
using namespace std;
class Student
{
public:
double m_age;
//无参构造函数
Student()
{
m_age = 20.4;
}
//打印
void print()
{
cout << m_age << endl;
}
//运算符重载
operator int()
{
return m_age;
}
};
int main()
{
Student a;
a.print();
cout << int(a) << endl;
//输出:20.4 20
return 0;
}
在给一个例子:
#include<iostream>
using namespace std;
class CFloat
{
public:
float m_ff;
//有参构造函数赋初值
CFloat(float f) :m_ff(f){}
operator int()
{
cout << "强制转化结果为:" << endl;
return (int)m_ff;
}
};
int main()
{
CFloat one(3.14);
cout << one.m_ff << endl;//输出3.14
cout << (int)one<< endl;//输出结果:3
//重载了之后就可以对对象进行操作可以不用写one.m_ff;
return 0;
}