[Effective C + +--024] If all parameters require type conversion, use the Non-member function for this

Source: Internet
Author: User

Introduction

Let's say we have a class like this:

1 classa{2  Public:3Aintnum =0,intDen =1) {};4     intNum ()Const;5     intDen ()Const;6     ConstAoperator* (Consta& RHS)Const;7};

When doing multiplication, we can take the following actions:

1     A A0 (12); 2     A A1 (13); 3 4     A Match = a0 * A1;     // same-type multiplication 5     Match = match * A0;    // same-type multiplication

The above operation is completely wood-problematic, so what if we want to achieve cross-type multiplication?

So we started trying to manipulate it.

1     2;       // OK        match = a0.operator * 22     2 * A0;       // Error     match = 2.operator * A0

Yes, A0 is a class object that includes the operator* function, so the compiler calls this function. However, 2 does not have a corresponding class, there is no corresponding operator* function.

In the successful operation above, the implicit conversion function is actually called, and in the compiler's opinion, the actual operation is:

1 Const A Temp (2);     // create a temporary object based on 2 2 match = a0 * TEMP;   // equivalent to A0.operator * (temp);

If we replace the constructor of a with the explicit function, then none of the above can be implicitly converted, and no single statement will be compiled.

Let's dig deeper, why match = 2 * A0; can't be done by implicit conversion?

The answer is: This parameter is a qualified participant in an implicit conversion only if the parameter is listed in the parameter column. Status equals "The object that the called member function belongs to"-that is, the metaphor parameter of this object, not a qualified participant. This is why the first compilation passes, and the second compilation does not pass: The first call is accompanied by a parameter placed in the parameter column, and the second call is No.

[Effective C + +--024] If all parameters require type conversion, use the Non-member function for this

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.