简体   繁体   English

将转换构造函数与运算符重载结合在一起

[英]Combining conversion constructor with operator overloading

Why is the conversion constructor not called implicitly for i2? 为什么没有为i2隐式调用转换构造函数?

class NumString
{
    public:
        NumString(const char*  s)
        {
        }

        int operator*( int i)
        {
            return 42;
        }
};


int main(void)
{
    int i1 = (NumString) "string" * 2;  //OK
    int i2 =  "string" * 2;             //ERROR
}

因为编译器不会在不涉及任何用户定义类型的情况下调用用户定义的转换。

The expression "string" * 2 involves just a const char * and an int , why should the compiler consider NumString in any way? 表达式"string" * 2仅涉及const char *int ,为什么编译器应以任何方式考虑NumString

If it worked like you expect, how would the complier be expected to choose the correct conversion if more than one class had a suitable converting constructor? 如果按预期工作,如果一个以上的类具有合适的转换构造函数,则编译器将如何选择正确的转换?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM