友元函数
友元函数是指某些虽然不是类成员却能够访问类的所有成员的函数。类授予它的友元特别的访问权。通常同一个开发者会出于技术和非技术的原因,控制类的友元和成员函数(否则当你想更新你的类时,还要征得其它部分的拥有者的同意)。友元函数是一个不属于类成员的函数,但它可以访问该类的私有成员。换句话说,友元函数被视为好像是该类的一个成员。友元函数可以是常规的独立函数,也可以是其他类的成员。实际上,整个类都可以声明为另一个类的友元。
为了使一个函数或类成为另一个类的友元,必须由授予它访问权限的类来声明。类保留了它们的朋友的 "名单",只有名字出现在列表中的外部函数或类才被授予访问权限。通过将关键字 friend 放置在函数的原型之前,即可将函数声明为友元。
#include <iostream>
using namespace std;
class MyTime{
private:
int hours;
int minutes;
public:
MyTime(): hours(0), minutes(0){}
MyTime(int h, int m): hours(h), minutes(m){}
MyTime operator+(const MyTime & t) const{
MyTime sum;
sum.minutes = this->minutes + t.minutes;
sum.hours = this->hours + t.hours;
sum.hours += sum.hours / 60;
sum.minutes %= 60;
return sum;
}
MyTime & operator+=(const MyTime & t){
this->minutes += t.minutes;
this->hours += t.hours;
this->minutes %= 60;
this->hours = this-> hours /60;
return *this;
}
MyTime operator+(int m) const{
MyTime sum;
sum.minutes = this->minutes + m;
sum.hours = this->hours;
sum.hours += sum.minutes / 60;
sum.minutes %= 60;
return sum;
}
friend MyTime operator+(int m, MyTime t){
return t + m;
}
string getTime() const {
return std::to_string(this->hours) + " hours and "
+ std::to_string(this->minutes) + " minutes.";
}
// 利用友元函数重载<<输出流,
// 此处注意返回值类型ostream为了return_value(cout) << endl;
// 输出符能继续连起来(否则可能变成0<<endl;)
friend ostream & operator<<(ostream & os, const MyTime & t){
string str = to_string(t.hours) + " h " + to_string(t.minutes) + "m.";
os<<str;
return os;
}
// 重载输入流
friend istream & operator>>(istream & is, MyTime & t){
is >> t.hours >> t.minutes;
t.hours += t.minutes / 60;
t.minutes %= 60;
return is;
}
};
int main(){
MyTime t1(2, 40);
cout<<(20+ t1).getTime()<<endl; // 使用友元函数
cout<<(t1+20).getTime()<<endl;
// 输出符从左往右运算
cout<<(t1 + 10)<<endl;
cin>> t1;
cout<<t1<<endl;
return 0;
}
运算符重载
#include <iostream>
using namespace std;
class MyTime{
private:
int hours;
int minutes;
public:
MyTime(): hours(0), minutes(0){}
MyTime(int h, int m): hours(h), minutes(m){}
MyTime operator+(const MyTime &t) const{
MyTime sum;
sum.minutes = this->minutes + t.minutes;
sum.hours = this->hours + t.hours;
sum.hours += sum.minutes / 60;
sum.minutes %= 60;
return sum;
}
MyTime & operator+=(const MyTime &t){
this->minutes += t.minutes;
this->hours += t.hours;
return *this;
}
MyTime & operator+(const string str) const{
MyTime sum = *this;
if(str == "1h"){
sum.hours = this->hours + 1;
}
return sum;
}
void getTime() const{
cout<< this->hours <<" : " << this->minutes << endl;
}
};
int main(){
MyTime t1 = MyTime(1, 20);
MyTime t2 = MyTime(2, 40);
MyTime tsum = t1 + t2;
tsum.getTime();
//MyTime t3 = tsum + "1h";
//t3.getTime();
(tsum + "1h").getTime();
return 0;
}
标签:友元,hours,const,sum,MyTime,运算符,重载,minutes
From: https://www.cnblogs.com/bai7/p/17959672