2012-01-03 39 views
1
#include <iostream> 
#include <fstream> 
using namespace std; 

class Integer 
{ 
    public: 
    int i; 

    Integer (int ll = 0, int k = 0) : i (ll) 
    { 
     cout << "\nconstructor A\n"; 
    } 

    Integer operator<< (const Integer& left, const Integer& right); 
}; 

Integer operator<< (const Integer& left, const Integer& right) 
{ 
    cout << "\ndsfdsfdsf : " << "===" << right.i << "\n"; 
    return left ; 
} 

int main() 
{ 
    Integer l; 

    l << 5 << 3 << 2; 

    return 0; 
} 

此代码给出上述标题错误,当我从< <操作者的声明删除关键字friend
这里没有什么私人的,为什么它会发生?错误:整数整数::运算<<(常量整数&,常量整数&)'必须采取只有一个参数

回答

3

当运算符声明不包含friend时,该声明声明了一个成员,并且成员将其类作为其隐式第一个参数。用这两个明确的参数,这为二元运算符提供了三个参数。

+0

所以,当一个声明是朋友,什么是类意下如何? – 2012-01-03 08:20:37

+1

@AnishaKaul:一个“朋友”适用于所有目的的普通功能,但具有特殊的访问权限。该行为与您在类的上方声明了一个自由函数'Integer运算符<<(const Integer&left,const Integer&right)',并且公开所有成员的行为相同。 – thiton 2012-01-03 08:23:05

0

正确的版本应该是这样的

#include <iostream> 
#include <fstream> 
using namespace std; 

class Integer 
{ 
    public: 
    int i; 

    Integer (int ll = 0, int k = 0) : i (ll) 
    { 
     cout << "\nconstructor A\n"; 
    } 

    Integer operator<< (const Integer& right) 
    { 
     cout << "\ndsfdsfdsf : " << "===" << right.i << "\n"; 
     return *this ; 
    } 
}; 



int main() 
{ 
    Integer l; 
    l << 5 << 3 << 2; 
    return 0; 
} 
+2

不正确,你的'operator <<'按值返回。 – jrok 2012-01-03 08:27:02

+0

希望它工作! – Hiren 2012-01-03 08:27:14