【问题标题】:Friend function inside class and outside class, what difference does it make?类内和类外的朋友功能,有什么区别?
【发布时间】:2017-02-16 05:46:41
【问题描述】:
#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++。我知道那是老派,但我们一定会使用它。

【问题讨论】:

  • &lt;iostream.h&gt; 不是标准标头。它从未成为标准的一部分。但在 1998 年第一个标准之前,它是 C++ 非官方定义的一部分,在注释参考手册(由 Stroustrup 和 Ellis 撰写)中。
  • conio.h 是特定于平台的非标准标头。与您的问题有关吗?
  • 编译器给出什么错误?
  • 你能告诉我们你是如何“定义类外的朋友函数”的吗?
  • @SingerOfTheFall 在他写的原始帖子中,他将如何在课堂之外实现它,但不是作为朋友,这是不可能的。它被 Biffen 编辑并删除。

标签: c++ oop operator-overloading


【解决方案1】:

问题是,您正在访问您的班级的私有成员 (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;
}

【讨论】:

  • @Biffen - 谢谢,我纠正了我的错误。派生类不能访问私有成员变量
  • 为了兼容性,我们应该在类定义中声明friends,并在类外再次声明,例如在头文件中并在源代码中定义。这对于某些编译器是必需的。
猜你喜欢
  • 2011-04-17
  • 1970-01-01
  • 1970-01-01
  • 2012-08-21
  • 1970-01-01
  • 1970-01-01
  • 2015-11-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多