operator重载操作符大家都会,今天来说一下operator操作隐式转换,就是可以将类类型隐式转换为类中存在的operator type中的type类型,比如类中存在operator type1(){…},则A可以隐式转换为type1类型。直接看例子
#include <iostream>
using namespace std;
class A
{
public:
explicit A(int a):m_a(a){}
operator int ()
{
return 5*m_a;
}
private:
int m_a;
};
int main()
{
A _a(1);
int b = _a;
cout<<"_a:"<<_a<<endl;
cout<<"b:"<<b<<endl;
return 0;
}
运行结果:
int b =_a; 这行中的_a按照类型解析进入 operator int(){}中执行,本来写到这儿就完了,但是博主突然想到既然按照类型来进行解析,那么看下面例子:
#include <iostream>
using namespace std;
class A
{
public:
explicit A(int a) :m_a(a) {}
operator double()
{
return 10 * m_a;
}
operator int()
{
return 5 * m_a;
}
private:
int m_a;
};
int main()
{
A _a(1);
int b = _a;
double c = _a;
//cout << "_a:" << _a << endl;
cout << "b:" << b << endl;
cout << "c:" << c << endl;
return 0;
}
运行结果:
运行结果验证了按照类型解析进入对应的operator TYPE(){}中执行,但是有没有发现代码中cout << “_a:” << _a << endl被注释掉了,因为直接输出的话会有歧义性,double和int都满足。
错误如下:
explicit也可以与operator显示转换操作符一起使用,具体看如下代码:
#include <iostream>
using namespace std;
class A
{
public:
A(int a):m_a(a) {}
int getA() { return m_a; }
private:
int m_a;
};
class B
{
public:
explicit operator A() { return A(1); }
private:
double m_b;
};
int main()
{
B b;
A a(b);
cout << a.getA() << endl;
//A a1 = b;
return 0;
}
运行结果:
类B中定义了对类型A的隐式转换,所以代码一目了然,如果去掉explicit的限制,则可以使用 A a1 = b;
人,总是要有一点精神的,不是吗?