c++ - 类内和类外的 friend 功能,有什么区别?

标签 c++ oop operator-overloading

#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++。我知道那是老派,但我们一定会使用它。

最佳答案

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

现在您可以在类之外编写实现并访问私有(private)变量。

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;
}

关于c++ - 类内和类外的 friend 功能,有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42265925/

相关文章:

c++ - 运算符 != 对于 std::reverse_iterator c++ 是不明确的

rust - 当输出值不属于类型时如何实现 std::ops::Index

c++ - 如何在类中声明一个 const size_t?

c++ - 从文件中读取输入,将第一个字母大写,将其他字母小写,然后输出到单独的文件中

c++ - C++将输入限制为整数,因此字母无效。

java - 如何使用基本接口(interface)引用调用扩展接口(interface)函数?

c++ - QObject::connect() 带有枚举参数

c++ - 这可以被认为是 C++ 中单例类的有效实现吗?

java - 如何清除 JTextField 中的输入错误并存储成功的错误

c++ - *this-> 不能作为函数使用