主题:友元函数使用
麻烦高手指点一下:程序中的display函数不放在Time类中,而作为类外的普通函数,然后分别在Time和Date类中将display声明为友元函数。在主函数中调用display函数,display函数分别引用Time和Date两个类的对象的私有数据,输出年、月、日和时、分、秒。
源程序:#include <iostream>
using namespace std;
class Date; //对Date类的提前引用声明
class Time //定义Time类
{public:
Time(int,int,int);
void display(Date &); //display是成员函数,形参是Date类对象的引用
private:
int hour;
int minute;
int sec;
};
class Date //声明Date类
{public:
Date(int,int,int);
friend void Time::display(Date &);
private:
int month;
int day;
int year;
};
Time::Time(int h,int m,int s) //类Time的构造函数
{hour=h;
minute=m;
sec=s;
}
void Time::display(Date &d) {cout<<d.month<<"/"<<d.day<<"/"<<d.year<<endl;
cout<<hour<<":"<<minute<<":"<<sec<<endl; }
Date::Date(int m,int d,int y)
{month=m;
day=d;
year=y;
}
int main( )
{Time t1(10,13,56); //定义Time类对象t1
Date d1(12,25,2004); //定义Date类对象d1
t1.display(d1);
return 0;
}
我自己做的但有错误不知道拿错了:
#include <iostream>
using namespace std;
class Date; //对Date类的提前引用声明
class Time //定义Time类
{public:
Time(int,int,int);
friend void display(Date &,Time &);
private:
int hour;
int minute;
int sec;
};
class Date //声明Date类
{public:
Date(int,int,int);
friend void display(Date &,Time &);
private:
int month;
int day;
int year;
};
Time::Time(int h,int m,int s) //类Time的构造函数
{hour=h;
minute=m;
sec=s;
}
Date::Date(int m,int d,int y)
{month=m;
day=d;
year=y;
}
int main( )
{Time t1(10,13,56); //定义Time类对象t1
Date d1(12,25,2004); //定义Date类对象d1
void display(Date &d,Time &t) {cout<<d.month<<"/"<<d.day<<"/"<<d.year<<endl;
cout<<t.hour<<":"<<t.minute<<":"<<t.sec<<endl; }
void display(&d1,&t1);
return 0;
}
麻烦高手研究一下,十分感谢
源程序:#include <iostream>
using namespace std;
class Date; //对Date类的提前引用声明
class Time //定义Time类
{public:
Time(int,int,int);
void display(Date &); //display是成员函数,形参是Date类对象的引用
private:
int hour;
int minute;
int sec;
};
class Date //声明Date类
{public:
Date(int,int,int);
friend void Time::display(Date &);
private:
int month;
int day;
int year;
};
Time::Time(int h,int m,int s) //类Time的构造函数
{hour=h;
minute=m;
sec=s;
}
void Time::display(Date &d) {cout<<d.month<<"/"<<d.day<<"/"<<d.year<<endl;
cout<<hour<<":"<<minute<<":"<<sec<<endl; }
Date::Date(int m,int d,int y)
{month=m;
day=d;
year=y;
}
int main( )
{Time t1(10,13,56); //定义Time类对象t1
Date d1(12,25,2004); //定义Date类对象d1
t1.display(d1);
return 0;
}
我自己做的但有错误不知道拿错了:
#include <iostream>
using namespace std;
class Date; //对Date类的提前引用声明
class Time //定义Time类
{public:
Time(int,int,int);
friend void display(Date &,Time &);
private:
int hour;
int minute;
int sec;
};
class Date //声明Date类
{public:
Date(int,int,int);
friend void display(Date &,Time &);
private:
int month;
int day;
int year;
};
Time::Time(int h,int m,int s) //类Time的构造函数
{hour=h;
minute=m;
sec=s;
}
Date::Date(int m,int d,int y)
{month=m;
day=d;
year=y;
}
int main( )
{Time t1(10,13,56); //定义Time类对象t1
Date d1(12,25,2004); //定义Date类对象d1
void display(Date &d,Time &t) {cout<<d.month<<"/"<<d.day<<"/"<<d.year<<endl;
cout<<t.hour<<":"<<t.minute<<":"<<t.sec<<endl; }
void display(&d1,&t1);
return 0;
}
麻烦高手研究一下,十分感谢