【问题标题】:how to overload operator<< when i have two objects??(has a relationship)当我有两个对象时如何重载运算符<<??(有关系)
【发布时间】:2017-05-28 23:55:13
【问题描述】:

我想额外显示对象的年龄,但我不知道如何在函数 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

【问题讨论】:

    标签: c++ overloading operator-keyword ostream


    【解决方案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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-03
      • 2018-05-30
      • 1970-01-01
      • 1970-01-01
      • 2018-10-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多