面向对象基础知识(四)static成员|友元

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yyycqupt

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值