如何重载operator<<当我有两个对象??(有关系)

时间:2017-05-28 23:55:14

标签: c++ overloading operator-keyword ostream

我想另外显示对象的年龄,但我不知道如何在函数ostream中调用对象日期,因为它只需要两个参数。有什么建议?? 我是否需要创建虚拟运算符并继承日期?

#ifndef HEARTRATE_H
#define HEARTRATE_H
#include <string>
#include <iostream>
#include "Date.h"

using std::string;
using std::cout;
using std::endl;

class HeartRate
{
public:
    HeartRate(string fn,string ln,Date d);
    string getfname();
    string getlname();
    Date getAge(Date& d);
    inline void printH(){
        cout<<Fname<<Lname<<date.getday()<<"/"<<date.getmonth()<<"/"<<date.getyear()<<"/"<<endl;
    }
    friend std::ostream&  operator<<(std::ostream& os,const HeartRate& hr){
        os<<"First name: "<<hr.Fname<<endl;
        os<<"Last name: "<<hr.Lname<<endl;
//I want to additional display the age of the object.
        os<<"The Date of birth is: "<<        
        return os;
    }
protected:
    string Fname;
    string Lname;
    Date date;
};

class Date
{
public:
    Date(int d,int m,int y);
    int getday(){return day;}
    int getmonth(){return month;}
    int getyear(){return year;}
    inline void print(){
        cout<<day<<"/"<<month<<"/"<<year;
    }
protected:
    int day;
    int month;
    int year;
};


#endif

1 个答案:

答案 0 :(得分:1)

您还必须重载类Date的插入运算符,以便能够将其用于该类的对象:

class Date
{
      public:
          friend ostream& operator << (ostream& out, const Date& theDate){
            out << theDate.day << " / " << theDate.month << " / " 
            << theDate.year;
              return out;
          }
      protected:
           int day;
           int month;
          int year;
  };

现在,您可以在班级HeartRate中写一下:

friend std::ostream&  operator<<(std::ostream& os,const HeartRate& hr){
    os<<"First name: "<<hr.Fname<<endl;
    os<<"Last name: "<<hr.Lname<<endl;
    //I want to additional display the age of the object.
    os << "The Date of birth is: "<<  hr.date;      
    return os;
}