• C++ Convert Operator和其他Operator的应用场景比较


    在看lftp的源代码的时候,发现这么一行:

    operator bool() const { return ... }

    一下子没想起来,这是什么语法,是operator overload么?不像阿,怎么不以函数的返回值打头呢?后来一查C++ Primer,明白了,这是convert operator,也就是将这个类如果要转化成bool值的话,就会调用到这个函数。convert operator以operator关键字打头,紧跟类型,然后是两个括号(括号中不能带有参数)。更具体的看C++ Primer和上面的注释。

    不过看明白了之后有个问题:

    operator int() const { ...... }
    bool operator<(int input) { ...... }

    就是如果这两个operator都定义了(一个是convert op, 一个是arithmetic op),那么,在实际代码中会用到哪个呢?为此,写了一小段测试代码:

    Code: Select all
    #include <iostream>
    using namespace std;

    class A {
        public:
            operator int() const { cout << "INT Convert function called..." << endl; return content; }
            bool operator<(int input) {
                cout << "Less operator function called..." << endl;
                if (content < input)
                    return true;
                else
                    return false;
            }
           
            void setContent(int value) { content = value; }
        private:
            int content;
    };

    int main()
    {
        A a;
        a.setContent(10);
        if (a < 100)
            cout << "Class A is less than 100..." << endl;
        else
            cout << "Class A is larger than 100..." << endl;

        cout << "The abs of class A is: " << abs(a) << endl;
        return 0;
    }


    测试结论是,第一个调用:if (a < 100),调用的是arithmetic op;第二个调用abs(a),使用的是convert op。所以,现在有答案了:

    1. 当有精确匹配时,比如a < 100这种,肯定使用精确匹配。因为如果使用convert op将a变成int,然后比较的话,要经过一个convert的过程;< operator这个函数是精确匹配,所以,肯定用这个。

    2. 第二个调用无法使用arithmetic op,所以,只能用convert op,将a转化成int。在实际编码过程中,除了这种情况,还有一些情况也会用到convert op。比如,class就定义了< operator,没定义>,那么,碰到if (a > 100)这种的时候,就只能使用convert op了。

    3. 避免出现ambiguous的情况。比如,如果我们代码这样写:if (a < 100.00),那么,编译就无法通过了。因为如果使用arithmetic op,那么,需要将100.00转化成int,才满足arithmetic op的参数要求;但是如果使用convert op,也需要将生成的int转化成double,才能和100.00做比较。这样一来,编译器就无法分辨这两种方案的优先级了,自然编译就会出错了。

    OK, That's all.
  • 相关阅读:
    duplicate symbols for architeture arm64 linker command failed with code 1(use-c to see invocation)
    Operation not permitted
    [笔试]常考算法
    过滤ST/退市股票
    python动态调用函数
    dataFrame 切片操作
    DataFrame概念与创建
    DataFrame 加减乘除
    DataFrame查找
    DataFrame操作
  • 原文地址:https://www.cnblogs.com/super119/p/1996147.html
Copyright © 2020-2023  润新知