2017-05-28 65 views
0

我想添加顯示對象的年齡,但我不知道如何在函數ostream中調用對象日期,因爲它只需要兩個參數。有什麼建議麼?? 我是否需要創建一個虛擬操作符並繼承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 

回答

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

非常感謝! –