2017-02-16 83 views
0
#include<iostream.h> 
#include<conio.h> 
class time 
{ 
    private: 
     int dd,mm,yy; 
    public: 
     friend istream & operator >>(istream &ip,time &t) 
     { 
      cout<<"\nEnter Date"; 
      ip>>t.dd; 
      cout<<"\nEnter Month"; 
      ip>>t.mm; 
      cout<<"\nEnter Year"; 
      ip>>t.yy; 
      return ip; 
     } 
     friend ostream & operator <<(ostream &op,time &t) 
     { 
      op<<t.dd<<"/"<<t.mm<<"/"<<t.yy; 
      return op; 
     } 

     void validate(); 
}; 

void time::validate() 
{ 
} 
int main() 
{ 
    clrscr(); 
    time t1; 
    cin>>t1; 
    cout<<t1; 
    getch(); 
    return 0; 
} 

它有什么不同?当我在类之外定义好友功能时,编译器给出了一个错误,但是当我在一个类中定义它时,它工作得很好。课内和课外的朋友功能,它有什么不同?

注意:我正在使用Turbo C++。我知道那是一所老学校,但我们必然会使用它。

+1

''不是标准标题。它从未成为标准的一部分。但在1998年的第一个标准之前,它是C++非官方定义的一部分,在注释参考手册中(由Stroustrup和Ellis提供)。 –

+0

'conio.h'是平台特定的非标准标头。这与你的问题有关吗? –

+0

编译器给出了什么错误? – Aeonos

回答

2

问题是,您正在访问您班级的私人成员(dd,mm,yy),只允许该班级或朋友的功能。所以你必须在类中声明这个函数是一个朋友,并且它可以在类之外实现。

class time 
{ 
private: 
    int dd,mm,yy; 
public: 
    friend istream & operator >>(istream &ip,time &t); // declare function as friend to allow private memeber access 
    friend ostream & operator <<(ostream &op,time &t); // declare function as friend to allow private memeber access 

    void validate(); 
}; 

现在您可以在类的外部编写实现并访问私有变量。

istream & operator >>(istream &ip,time &t) 
{ 
    cout<<"\nEnter Date"; 
    ip>>t.dd; 
    cout<<"\nEnter Month"; 
    ip>>t.mm; 
    cout<<"\nEnter Year"; 
    ip>>t.yy; 
    return ip; 
} 

ostream & operator <<(ostream &op,time &t) 
{ 
    op<<t.dd<<"/"<<t.mm<<"/"<<t.yy; 
    return op; 
} 
+0

@Biffen - 谢谢,我纠正了我的错误。私有成员变量不能被派生类访问 – Aeonos