c++静态数据成员和静态成员函数、友元函数和友元类

博客介绍了类的静态数据成员、静态成员函数、友元函数和友元类的相关知识。静态数据成员由类的所有对象维护同一拷贝,需在类外定义初始化;静态成员函数可通过类名调用,只能引用静态成员;友元函数在类内声明但非类成员;友元类单向且无传递性、不可派生。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

静态数据成员

用static声明该类的所有对象维护该成员的同一个拷贝

必须在类外定义和初始化,用(::)来指明所属的类

可用对象名访问也可以用类名访问

 

静态成员函数

类外代码可以使用类名和作用域操作符来调用静态成员函数

静态成员函数只能引用属于该类的静态数据成员或者静态成员函数

 

#include <iostream>
using namespace std;

class Point
{
public:
	Point(int x = 0, int y = 0) :x(x),y(y)
	{
count++;
	
	}
	
	Point(Point &p) {
		x = p.x;
		y = p.y;
		count++;
	}
	~Point() { count--; }
	int getX() { return x; }
	int getY() { return y; }
	static void showCount() {
		cout << "Object number:" << count << endl;
	}

private:
	int x, y;
	static int count;
};
int Point::count = 0;
int main() {
	Point::showCount();
	Point a(4, 5);
	cout << "a" << a.getX() << ":" << a.getY() << endl;
	a.showCount();
	Point b(a);
	cout << "b" << b.getX() << ":" << b.getY()<< endl;
	a.showCount();
}
结果:
Object number:0
a4:5
Object number:1
b4:5
Object number:2
请按任意键继续. . .


友元函数

在类内声明用friend,不是类内成员。

#include <iostream>
#include <cmath>
using namespace std;

class Point
{
public:
	Point(int x = 0, int y = 0) :x(x),y(y){}

	int getX() { return x; }
	int getY() { return y; }
	friend float dist(Point&p1, Point&p2);        //友元函数声明

private:
	int x, y;
};
float dist(Point&p1, Point&p2) {        //友元函数定义
	double x = p1.x - p2.x;
	double y = p1.y - p2.y;
	return sqrt(x*x + y*y);
}

int main() {
	Point p1(1, 1);
	Point p2(4, 5);
	cout << dist(p1, p2) << endl;
}
结果:
5
请按任意键继续. . .

友元类

单向的 ,不具有传递性,不可派生。谁是谁的友元类必须写出来,a是b的友元类,a可以访问b的私有成员,b不可以访问a的私有成员。

#include <iostream>
#include <cmath>
using namespace std;

class Point
{
public:
	Point(int x = 0, int y = 0) :x(x),y(y){}

	int getX() { return x; }
	int getY() { return y; }
	friend float dist(Point&p1, Point&p2);
	friend class Line;    //友元类声明

private:
	int x, y;
};
class  Line{                //友元类定义
public:
private:
};
float dist(Point&p1, Point&p2) {
	double x = p1.x - p2.x;
	double y = p1.y - p2.y;
	return sqrt(x*x + y*y);
}

int main() {
	Point p1(1, 1);
	Point p2(4, 5);
	cout << dist(p1, p2) << endl;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值