#include<iostream>
using namespace std;
//ImplictChange只有一个数据成员x
class ImplictChange
{
public:
ImplictChange(int a) : x(a) {} //explicit可以防止隐式转换
friend bool operator==(const ImplictChange& rhs,const ImplictChange& lhs)
{
return(rhs.x == lhs.x);
}
private:
int x;
};
//用代理类来限制隐式转换
//原理:隐式转换只能被调用一次
class NoImplictChange
{
public:
//增加代理类
class Proxy
{
public:
Proxy(int a) : x(a) {}
int getX() const
{
return(x);
}
private:
int x;
};
NoImplictChange(const Proxy& p) : pro(p) {}
friend bool operator==(const NoImplictChange& rhs,const NoImplictChange& lhs)
{
return(rhs.pro.getX() == lhs.pro.getX());
}
private:
Proxy pro;
};
int main()
{
ImplictChange a(1);
if(1 == a) //此处就出现了隐式转换
{
cout << 1 << endl;
}
NoImplictChange b(1);
if(1 == b)
{
cout << 1 << endl;
}
return(0);
}
使用代理类限制隐式转换
最新推荐文章于 2022-10-11 09:52:18 发布