定义
c++里有一些隐式类型转换,比如:double附值给int,内容会被截断;int和double类型的值进行运算,int自动转换为double型等。
所谓重载自动类型转换,就是用户自己定义类的自动转换方式。。。。、
我越来越懒了,直接贴代码吧。
operator type(){
//type为 `转换到的类型`
//不需要指定返回值类型,因为返回的肯定是 `要转换到的类型`
}
可以重载多个
operator type1(){
//code...
}
operator type2(){
//code...
}
例子
例如一个类有三个成员:int a;string s;char c;我们在类中写道:
operator int(){
return a+s.size()+c;
}
//当遇到需要转换的地方,系统就会按上述规则进行转换成int型。
注意:所谓转换,原对象并没有改变
完整例子
#include<iostream>
#include<sstream>
#include<cmath>
using namespace std;
class Vector2 {
public:
Vector2() {}
Vector2(int x, int y) :x(x), y(y) {}
int x, y;
};
class Vector3 {
public:
Vector3() {}//无参构造函数
Vector3(int x, int y, int z) :x(x), y(y), z(z) {}//有参构造函数
int x, y, z;
operator Vector2 () {
return Vector2(x, y);//自动转换出Vector2类型
}
operator double() {//自动转换出int,为模长
return sqrt(x*x + y * y + z * z);
}
};
int main() {
Vector3 v3(3, 4, 5);
double d = v3;//将Vector3类型附给double型,自动类型转换
double dd = d + v3;//将Vector3和double型相加,自动类型转换
cout << d << endl;//结果 7.07107
cout << dd << endl;//结果 14.1421
Vector2 v2 = v3;将Vector3类型附给Vector2型,自动类型转换
cout << "("<<v2.x << "," << v2.y << ")" << endl;//结果 (3,4)
system("pause");
return 0;
}
补充
当同时有 成员函数重载运算符
、友元函数重载运算符
、重载自动类型转换
时,优先及为:
- 成员函数重载运算符
- 友元函数重载运算符
- 重载自动类型转换
#include<iostream>
#include<sstream>
#include<cmath>
using namespace std;
class Vector3 {
public:
Vector3() {}
Vector3(int x, int y, int z) :x(x), y(y), z(z) {}
int x, y, z;
operator double() {
return sqrt(x*x + y * y + z * z);
}
int operator+(double d) {
return x + y + z + d;
}
};
char operator+(double d, const Vector3& v) {
return 'A';
}
char operator+( const Vector3& v,double d) {
return 'B';
}
int main() {
Vector3 v3(3, 4, 5);
double d = 1.0;
cout << (v3 + d) << endl;//结果 13,优先成员函数
cout << (d+v3) << endl;//结果 A,没有重载成员运算符函数,优先友元函数
cout<<(d-3)<<endl;//结果 4.07107,自动转出double
cout << v3 << endl;//结果 7.07107,自动转出double
system("pause");
return 0;
}