class Date
{
public:
Date()
:_year(10)
{
}
void Print()
{
cout << _year << "-" << _mouth << "-" << _day << endl;
}
private:
//C++11
//声明时给缺省值
int _year=0;
int _mouth=1;
int _day=1;
//类里面声明
static int n;
};
//在类外面定义
int Date::n = 1;
int main()
{
Date d1;
return 0;
}
2.友元:类外函数想要访问成员变量
class Date
{
friend void f(Date& d);//友元函数
public:
void Print()
{
cout << _year << "-" << _mouth << "-" << _day << endl;
}
private:
int _year=0;
int _mouth=1;
int _day=1;
};
void f(Date& d)
{
d._year = 10;
cout << d._year << endl;
}
int main()
{
Date d1;
d1.Print();
return 0;
}
3.运算符重载<< >> 的友元函数:
class Date
{
friend istream& operator>>(istream& in, Date& d);
friend ostream& operator << (ostream& out, Date& d);
public:
Date(int year = 0, int mouth = 1, int day = 1)
:_year(year)
,_mouth(mouth)
,_day(day)
{
}
//第一种方式
/*void operator << (ostream & out)
{
out << _year << "/" << _mouth << "/" << _day << endl;
}*/
private:
int _year = 0;
int _mouth = 1;
int _day = 1;
};
//第二种方式
ostream & operator << (ostream& out,Date& d)
{
out <<d. _year << "/" << d._mouth << "/" <<d. _day << endl;
return out;
}
//cout->ostream
//cin->istream
istream& operator>>(istream& in, Date& d)
{
in >> d._year >> d._mouth >> d._day ;
return in;
}
int main()
{
Date d1(2020,4,20);
Date d2(2020, 4, 21);
cout << d1 << d2 << endl;
//第二种方式
cout << d1;//operator<<(cout,d1)
//第一种方式
//d.operator<<(cout);
//d1 << cout;//d1.operator<<(cout);
int i = 0, j = 0;
cout << i << j << endl;
cin >> d1 >> d2;
int x = 1;
double y = 1.11;
//为什么能自动识别类型,因为函数重载调用的是不同的函数
cout << x;//cout.operator(&cout,x);
cout << y;//cout.operator(&cout,x);
return 0;
}
4.友元类:
class Time
{
friend class Date;//声明日期类为时间类的友元类,则在日期类中就直接访问Time类中的私有成员
public:
Time(int hour = 0, int minute = 0, int second = 0)
:_hour(hour)
,_minute(minute)
,_second(second)
{}
private:
int _hour;
int _minute;
int _second;
};
class Date
{
public:
Date(int year=1900,int mouth=1,int day=0)
:_year(year)
,_mouth(mouth)
,_day(day)
{}
void SetTimeOfDate(int hour, int minute, int second)
{
//直接访问时间类的私有的成员变量
_t._hour = hour;
_t._minute = minute;
_t._second = second;
}
private:
int _year;
int _mouth;
int _day;
Time _t;
};
int main()
{
return 0;
}