operator用于隐式类型转换

发布时间 2023-03-22 21:09:34作者: 多一些不为什么的坚持

C++中的operator主要有两种作用,一是操作符重载,二是自定义对象类型的隐式转换。在上面提到的point类中,我们提到如果构造函数没有默认参数,隐式转换的时候就会编译出错,但是如果我们利用operator的第二个作用,就可以自定义隐式转换类型。

#include <iostream>
#include <string>
using namespace std;

class point {
    public:
        point(int x, int y):x(x),y(y) {
            cout << "constructor" << endl;
        }

        bool operator()(int x, int y) {
            cout << "opearator overload" << endl;
            return x>this->x && y>this->y;
        }

        operator string() {
            cout << "type convert" << endl;
            string str = "(" + x;
            str += "," + y;
            str += ")";
            return str;
        }
    private:
        int x,y;
};

int main()
{
    // part1
   point p1(5,6);
   if(p1(10,9)){
       cout << "point(10,9) is larger than  point(5,6)" << endl;
   }
   
    // part2
   string str(p1);
	cout << str;
}

运行结果如下:

 

主函数的part1调用的是operator的重载作用,我们主要探讨part2的隐式转换作用。我们往string类的构造函数中传递的point类,显然string类中必然没有以point类为参数的构造函数,但是从运行结果来看,这次构造是成功的。

 

在这个例子中,string str(p1)是将point类对象转换成string类对象,使用的是string类的隐式构造(转换),string类不存在有默认参数的构造函数,也不存在以point类为参数的构造函数,那么string类就需要去point类中去找以operator算子修饰的将point类转为string类的转换函数,并调用该函数,最终返回的string临时对象,被string类用来拷贝构造成一个新的string对象str

如果string类有默认参数的构造函数,那么string str(p1)会隐式调用该默认参数的构造函数来构造string。对于没有默认参数的构造函数情况下,类的隐式类型转换,是使用一个其他类型构造当前类的临时对象,并用此临时对象来构造当前对象,这种转换必须有其他类型的构造函数支持;而operator算子的隐式类型转换,就是使用当前类型对象生成另一个类型的对象(正好与没有默认参数构造函数情况下,类的隐式转换相反),这种转换必须有operator算子的支持。

 参考:

C++——隐式类型转换_隐式转化 c++_linengcs的博客-CSDN博客