类型转换
类型转换函数的特征:
1)
2)
3)
语句,在return语句中返回目标类型数据或调用目标类的构造函数。
类型转换函数主要有两类:
1)
2 ) 对象向不同类的对象的转换:
调用场景:
通常用于左值赋值表达式中的隐式转换
例程1:
//通过类型转换函数求半径为5的圆的面积
//并将其存储在float型变量中打印输出
#include <iostream>
using namespace std;
class CArea
{
float area;
public:
CArea()
{
area=0;
}
CArea(float a) //重载含有一个参数的构造函数
{
area=a;
}
void getArea()
{
cout<<area<<endl;
}
void setArea(float a)
{
area=a;
}
operator float() //类型转换函数
{
//将面积类对象转换为float型数据
return area;
}
};
class CCircle
{
float R;
public:
void getR()
{
cout<<R<<endl;
}
void setR(float r)
{
R=r;
}
operator CArea() //类型转换函数
{ //将圆类对象转为面积类对象
float area=3.1415926*R*R;
return (CArea(area));
}
};
void main()
{
CCircle cir;
CArea are;
float a;
cir.setR(5);
cir.getR(); //打印圆的半径
are.getArea(); //打印转换前的面积
are=cir; //将圆类对象转为面积类对象
are.getArea(); //打印转换后的面积
a=are; //将面积类对象转换为float型数据
cout<<a<<endl;
}
操作符重载
操作符重载的概念:
注意事项:
1)
2)
3)
4)
5)
.
*
::
? :
sizeof 操作数的字节数
例程2:
#i nclude <iostream>
using namespace std;
class employee
{
int salary;
public:
void setSalary(int s)
{
salary=s;
}
void getSalary()
{
cout<<salary<<endl;
}
bool operator >(const employee & e)//重载大于号操作符
{
if(salary > e.salary)
return true;
else
return false;
}
};
void main()
{
employee emp1,emp2;
emp1.setSalary(1000);
emp2.setSalary(2000);
if (emp1 > emp2)
{
cout<<"emp1比emp2工资高"<<endl;
}
else
{
cout<<"emlp1没有emp2工资高"<<endl;
}
}
本文深入探讨了C++中的类型转换函数及其特征,包括转换函数的定义、参数、返回值等关键要素。同时,文章详细介绍了操作符重载的概念,解释了如何将现有操作符与成员函数关联,以及注意事项。通过示例代码,展示了如何实现对象到基本数据类型及不同类对象之间的转换,以及如何重载大于号操作符进行比较。
4473

被折叠的 条评论
为什么被折叠?



