0

在我的班级定义中,我有以下朋友功能:

      friend  ostream& operator << (ostream& out, const Person& p1);

      friend istream& operator >> (ostream& out Person& p1);

在我的实现文件中:

       ostream& operator << (ostream& out, const Person& p1)
      {
       out<< p1.age; //this is a private variable
      }

      istream& operator << (istream& in, Person& p1)
      {
       in >> p1.age; //this is a private variable
      }

但是当我编译这个时,我得到一个错误,说“ostream”没有命名一个类型friend ostream& operator(ostream& out, const Person& p1) .. istream 也是一样。由于这些是友元函数,它们可以访问私有变量,即年龄,那么问题是什么?

4

1 回答 1

1

所以首先,你的函数应该返回一些东西,所以:

ostream& operator << (ostream& out, const Person& p1)
  {
   return out<< p1.age; //this is a private variable
  }

istream& operator << (istream& in, Person& p1)
  {
   return in >> p1.age; //this is a private variable
  }

你应该记得添加include <iostream>标题。和using namespace std;

最重要的是一个错字

friend istream& operator >> (istream& out Person& p1);
于 2013-10-25T10:37:09.223 回答