博客
关于我
C++ 极简总结——类(二)
阅读量:253 次
发布时间:2019-03-01

本文共 1444 字,大约阅读时间需要 4 分钟。

类的静态成员

在C++中,类的静态成员是指那些在类的范围内所有对象共享的成员。静态成员可以是数据成员或函数,都是通过类名直接访问的。

静态数据成员

静态数据成员属于类的属性,它们的存储单元是与类相关联的,而不是与任何具体的对象相关联。静态数据成员的特点包括:必须手动初始化,不能在构造函数中进行初始化,初始化时需要使用类名来限定。

举个例子,以下代码中point_count是一个静态数据成员:

```cpp #include
using namespace std; class Point { public: static int point_count; Point(int x = 0, int y = 0); ~Point(); private: int _x; int _y; }; Point::Point(int x, int y) { _x = x; _y = y; point_count++; cout << "Constructor"; cout << "Point_Num = " << point_count << endl; } ~Point() { // destructor code } static void show_count(); static int point_count;

静态成员函数

静态成员函数的定义和调用方式与普通成员函数类似,但在定义时必须加上static关键字。静态成员函数可以直接访问类的静态成员,而不需要依赖任何对象。

例如,以下代码中show_count是一个静态成员函数:

```cpp #include
using namespace std; class Point { public: Point(int x = 0, int y = 0); ~Point(); static void show_count(); private: int _x; int _y; static int point_count; }; void Point::show_count() { cout << "Point Num = " << point_count << endl; }

类的友元

友元是C++提供的一种机制,允许外部函数或类访问类的私有或保护成员。友元可以是函数或类,通过在类中声明友元来实现。

友元函数

友元函数是指在类中声明为friend的函数。这些函数可以访问类的所有成员,包括私有和保护成员。友元函数通常用于提高代码的灵活性和效率。

例如,以下代码中pointDistance是一个友元函数:

```cpp #include
#include
using namespace std; class Point { public: Point(int x = 0, int y = 0); ~Point(); static void show_count(); friend double pointDistance(const Point a, const Point b); private: int _x; int _y; static int point_count; };

友元类

类也可以声明另一个类作为友元。例如,如果类B在定义中声明类A为友元,那么类A可以访问类B的所有成员,而不需要依赖任何对象。

友元的使用虽然提供了灵活性,但也可能导致类的封装性被破坏,因此在使用友元时需要谨慎考虑。

转载地址:http://jnrx.baihongyu.com/

你可能感兴趣的文章
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No qualifying bean of type XXX found for dependency XXX.
查看>>
No resource identifier found for attribute 'srcCompat' in package的解决办法
查看>>
Node.js 文件系统的各种用法和常见场景
查看>>
node.js 配置首页打开页面
查看>>
node.js+react写的一个登录注册 demo测试
查看>>
Node.js安装与配置指南:轻松启航您的JavaScript服务器之旅
查看>>
nodejs libararies
查看>>
nodejs-mime类型
查看>>
nodejs中Express 路由统一设置缓存的小技巧
查看>>
Node入门之创建第一个HelloNode
查看>>
NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
查看>>
npm run build 失败Compiler server unexpectedly exited with code: null and signal: SIGBUS
查看>>
npm WARN deprecated core-js@2.6.12 core-js@<3.3 is no longer maintained and not recommended for usa
查看>>
npm和yarn的使用对比
查看>>
npm报错unable to access ‘https://github.com/sohee-lee7/Squire.git/‘
查看>>
npm的问题:config global `--global`, `--local` are deprecated. Use `--location=global` instead 的解决办法
查看>>
NR,NF,FNR
查看>>