运营商LT;<和运算符>>重载函数

时间:2013-10-25 04:12:08

标签: c++ function

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

      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”并没有说出类型朋友ostream&amp;运算符(ostream&amp; out,const Person&amp; p1)..同样适用于istream。由于这些是朋友功能,他们可以访问私有变量,即年龄,所以问题是什么?

1 个答案:

答案 0 :(得分: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);