c++ - 当我有两个对象时如何重载运算符<<??(有关系)

标签 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

最佳答案

您还必须重载类 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;
}

关于c++ - 当我有两个对象时如何重载运算符<<??(有关系),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44233080/

相关文章:

C++ 运算符 + 重载

c# - 我怎样才能把函数放在其他cs文件中?

c++ - gcc 4.5.1 虚拟继承问题

c++ - 使用鼠标拖动旋转 QLabel

c# - 为什么编译器不能在这种重载解析情况下告诉更好的转换目标? (协方差)

性能差和高 CPU 负载调优的 Mysql - cs-cart linux

C++ 重载 new[] 查询 : What size does it take as parameter?

c++ - clockTick 函数未在此范围内声明

c++ - 将表示为链表的两个大数相乘

c# - 重载时无限递归==