"Why is too many parameters prompted without adding friend"

Source: Internet
Author: User
1 # include <iostream> 2 using namespace STD; 3 4 class complex 5 {6 double real, imag; 7 public: 8 complex (Double R, double I ): real (R), imag (I) {} 9 complex operator + (Double R); 10 complex operator + (Double R, const complex & C); // change it to the following: friend complex operator + (Double R, const complex & C) 11 void valueget () {12 cout <real <"," <imag <Endl; 13} 14}; 15 complex: Operator + (double r) 16 {17 return complex (Real + R, IMAG); 18} 19 20 int main () 21 {22 complex C1 (3, 2); 23 C1 = C1 + 3; 24 c1.valueget (); 25}

The above program compiler will report an error. The error is

Error 1 error c2804: Binary 'operator + 'hasToo parameter Parameters

The reason is that when the operator is overloaded, it can be reloaded as a member function or a common function.

When the overload is a common function, the number of parameters should be the number of operators.

When the overload is a member function, the number of parameters should be equal to the number of operators minus one.

For the "+" to be overloaded here, the number of operators is 2. If the overload is a common function, the number of parameters should be 2. If the reload is a member function, the number of parameters should be 1.

This corresponds to the addition of friend. When friend is added, it indicates that although this function is inside the class, it is a common function rather than a member function. The parameter must be 2. Without friend, this is a member function of the class. The parameter should be set to one.

 

"Why is too many parameters prompted without adding friend"

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.