C + +: All parameters that use non-member functions (NON-MEMBER) to handle functions require type conversions

Source: Internet
Author: User
Tags require

Some functions, all parameters need to use type conversion, such as multiplication, write a rational number class rational, need to perform multiplication operations:

function satisfaction: Rational = rational*double; Rational = double*rational; You need to use a non-member function (Non-member);

The initiator of a member function must be a class, because a double type may occur before the multiplication can be performed, so you should use a non-member function;

When executing: that is, Rational = rational*rational (double); Rational = rational (double) *rational, an implicit conversion occurred.

Code:

* * * test.cpp * *  Created on:2014.04.22 * 
 author:spike/
      
/*eclipse CDT, gcc 4.8.1* /
      
#include <iostream>/  
      
/Rational number  
class Rational {public  
:  
    rational (double numerator = 0, Double denominator = 1):  
        m_n (numerator), m_d (denominator) {}  
    double numerator () const {return m_n;};  
    Double denominator () const {return m_d;};  
    Double value () {return (m_n/m_d);}  
Private:  
    double m_n;  
    Double m_d;  
};  
      
Const Rational operator* (const rational& LHS,  
        const rational& RHS) {return  
    Rational (Lhs.numerator () *rhs.numerator (),  
            lhs.denominator () *rhs.denominator ());  
}  
      
int main (void) {  
    Rational Onefourth (1, 4);  
    Rational result;  
    result = Onefourth * 3.5;  
    result = 3.5 * Onefourth;  
    Std::cout << "result =" << result.value () << Std::endl;  
      
    return 0;  
}

Output:

result = 0.875

Author: csdn Blog spike_king

More Wonderful content: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/cplus/

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.