У меня есть два класса; один называется Date
а другой - University
. Класс Date
имеет два перегруженных оператора: operator<<
и operator>>
чтобы взять данные и распечатать их.
Date.h
#ifndef DATE_H_
#define DATE_H_
#include <iostream>
#include "University.h"
using namespace std;
class Date {
public:
Date(); // constructor
void setDate( int d, int m, int y ); // set day, month, year
friend ostream & operator<<(ostream & out, Date & x); // print date format "month dd, yyyy (example: January 11, 2013)
friend istream & operator>>(istream & In, Date & x); // to read date
private:
int day;
int month;
int year; //
};
#endif
Date.CPP
#include <iostream>
#include "Date.h"
#include "University.h"
using namespace std;
Date::Date()
{}
void Date::setDate( int d, int m, int y )
{
day=d;
month=m;
year=y;
}
ostream & operator<<(ostream & out, Date & x)
{
out<< x.month << "/" << x.day << "/" << x.year ;
return out;
}
istream & operator>>(istream & in, Date & x)
{
in>> x.day >> x.month >> x.year ;
return in;
}
University
класс имеет объект типа Date
с именем establishDate
, и я должен использовать это, чтобы напечатать дату вместе с названием университета и местоположением.
Здесь класс University
:
// University.h
class University {
public:
University (); // constructor
friend ostream & operator<<(ostream & out, University & x); // print the university data
friend istream & operator>>(istream & in, University & x); // to read university data
private:
const static string uname;
string location;
Date establishDate;
};
const string uname = "London University";
Как использовать объект establishDate
?
Я думаю, вы хотите что-то вроде ниже:
ostream & operator<<(ostream & out, University & x)
{
out<< x.uname << " in " << x.location << " has been established in: " << x.establishDate.month << "/" << x.establishDate.day << "/" << x.establishDate.year ;
return out;
}
Это работает, потому что оператор является другом и, следовательно, имеет доступ к частным членам.
cout << establishedData
например?