简体   繁体   English

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

[英]how to overload operator<< when i have two objects??(has a relationship)

I want to additionaly display the age of object but i do not know how to call object date in function ostream since it takes only two arguments. 我想另外显示对象的年龄,但是我不知道如何在函数ostream中调用对象日期,因为它仅需要两个参数。 Any suggestions?? 有什么建议么?? Do i need to create a virtual operator and inherite Date? 我需要创建一个虚拟运算符并继承Date吗?

#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

You have also to overload the insertion operator for the class Date to be able to use it for objects of that class: 您还必须重载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;
  };

Now in your class HeartRate you can simply write: 现在,在您的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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM