码迷,mamicode.com
首页 > 其他好文 > 详细

关于“为什么不加friend就会提示参数过多”

时间:2014-09-06 22:26:23      阅读:310      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   io   ar   strong   div   sp   

 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);//改为以下即可:friend Complex operator+ (double r, const Complex & c)
11     void ValueGet(){
12         cout << real << "," << imag << endl;
13     }
14 };
15 Complex 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 }

上述程序编译器会报错,错误是

Error 1 error C2804: binary ‘operator +‘ has too many parameters

原因就是,重载运算符时可以重载为成员函数和普通函数两种形式。

当重载为普通函数时,参数个数理应为运算符目数。 

当重载为成员函数时,参数个数理应为运算符目数减一。

对于这里要重载的+号而言,运算符目数为2.如果重载为普通函数,参数个数应该为2。如果重载为成员函数,参数个数应该为1.

而这正对应于这里的加不加friend。当加了friend时,表示这个函数虽然是在类内部,但是却是一个普通函数而不是成员函数。参数应该为2个。而不加friend表示这是一个类的成员函数,参数应该为1个才对。

 

关于“为什么不加friend就会提示参数过多”

标签:style   blog   color   os   io   ar   strong   div   sp   

原文地址:http://www.cnblogs.com/leoshuyi/p/3959865.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!