Static成员
静态成员变量
static修饰的成员变量叫做静态成员变量。
静态成员变量存储在静态区。
静态成员变量在类中声明,定义只能在类外,定义时不写static关键字。
静态成员变量被类的所有对象共享,不属于任何一个对象。
若修饰静态成员变量的访问限定符是public,可在类外这样访问 类名::静态成员变量。
静态成员函数
static修饰的成员函数叫做静态成员函数。
静态成员函数存储在静态区。
静态成员函数没有this指针所以不能访问成员变量和成员函数,只能访问静态成员函数和静态成员变量。但成员函数可以访问访问静态成员函数和静态成员变量。
静态成员函数被类的所有对象共享,不属于任何一个对象。
若修饰静态成员函数的访问限定符是public,可在类外这样访问 类名::静态成员函数。
可以用静态成员解决计算属于一个类的对象有多少个?
#include <iostream>
using namespace std;
class A {
public:
A() {
cnt++;
}
A(const A& a) {
cnt++;
}
static int getCnt() {
return cnt;
}
~A(){
cnt--;
}
private:
static int cnt;
};
int A::cnt = 0;
int main() {
A a1;
A a2;
A a3(a1);
cout << A::getCnt() << endl;
return 0;
}
友元
友元函数
类外的函数要想访问类里的私有成员,必须成为类的友元函数。
成为类的友元函数,就是在类中声明函数且在声明前加friend。
重载运算符>>和<<必须用友元函数实现。
#include <iostream>
using namespace std;
class Date {
private:
int _year;
int _month;
int _day;
public:
Date(int year = 0, int month = 1, int day = 1)
:_year(year)
, _month(month)
, _day(day) {};
friend ostream& operator<<(ostream& out, const Date& d);
friend istream& operator>>(istream& in, Date& d);
};
ostream& operator<<(ostream& out, const Date& d) {
out << d._year << " " << d._month <<" " << d._day ;
return out;
}
istream& operator>>(istream& in, Date& d) {
cin >> d._year >> d._month >> d._day;
return in;
}
int main() {
Date d1(2023, 10, 24);
Date d2;
cin >> d2;
cout << d1 << endl;
cout << d2 << endl;
return 0;
友元类
如果A类想直接访问B类的私有成员,那么将将这个A类设为B类的友元类。
友元关系是单向的。A类是B类的友元类,A类中可以访问B类的私有成员,B类中不能访问A类的私有成员。
友元不能传递。A类是B类的友元类,B类是C类的友元类,不能得到A类是C类的友元类。
友元关系不能继承。
#include <iostream>
using namespace std;
class Time {
friend class Date;
private:
int _hour;
int _minute;
int _second;
};
class Date {
private:
int _year;
int _month;
int _day;
Time _time;
public:
Date(int year = 0, int month = 1, int day = 1)
:_year(year)
, _month(month)
, _day(day) {};
void setDateOfTime(int hour, int minute, int second) {
_time._hour = hour;
_time._minute = minute;
_time._second = second;
}
};
int main() {
Date d1(2023, 10, 24);
d1.setDateOfTime(19, 11, 30);
return 0;
}