友元函数
example
#include <iostream>
using namespace std;
class Date {
public:
Date(int _year, int _month, int _day) : year(_year), month(_month), day(_day) {}
friend ostream& operator<<(ostream& out, const Date& d);
private:
int year;
int month;
int day;
};
ostream& operator<<(ostream& out, const Date& d) {
out << d.year << "/" << d.month << "/" << d.day << endl;
return out;
}
int main() {
Date d1(3, 5, 11);
Date d2(2, 2, 2);
cout << d1 << d2;
}
notion
- 友元函数可以访问私有(private)和受保护(protected)成员,但不能访问公有(public)成员。
- 友元函数不能用 const 进行修改。
- 一个函数可以被多个类声明为友元函数。
friend class
code
class Date;
class Time{
friend class Date;
public:
Time (){}
private:
int hour;
int min;
int sec;
};
class Date{
private:
int year;
int month;
int day;
Time _t;_
public:
void setTime(int _hour,int _min,int _sec){
_t.hour=_hour;
_t.min=_min;
_t.sec=_sec;
}
};
notion
Class time 不能访问 Class Date,
但 Class Date 可以访问 Class Time;
Time->Date ERROR!
Date->Time AC!
the solution
class Date{
friend class Time;
......
}
;
Attention
friendship关系不能传递
如果A是B的友元,
B是C的友元;
但是C不是A的友元
static 成员变量
- 多个对象维护同一个类的static 成员函数
- 必须在类外定义类内声明,且类外不要加static 类内要;
- 脱离对象独立存在的要分配存储空间的
访问
- 对象名.静态成员名
- 类名.静态成员名
//init
int stu1.s=0;
int student:: s=0;
static 成员函数
- 静态成员函数才可以访问static成员变量
- 无this指针,所以不能用const 修饰
- 静态成员函数不能访问非静态成员函数和变量
- 不需要生出变量就能使用
- 类能直接访问static成员函数
Explicit
当你用"explicit"修改构造函数时,可以禁止函数的隐式转换。
Const
常成员函数
cosnt 修饰其this指针
*const this
不能修改成员变量
不能调用该类中没有用const 修饰的成员函数
常对象
- 不能调用任何类的成语函数,一旦定义,常对象就不能修改
- 只有类的常成员函数才可以访问该类的常对象,且const 成员函数不修改对象
- 不能修改
- 只能在定义是有构造函数初始化