博客
关于我
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/

你可能感兴趣的文章
npm发布自己的组件UI包(详细步骤,图文并茂)
查看>>
npm和yarn清理缓存命令
查看>>
npm和yarn的使用对比
查看>>
npm如何清空缓存并重新打包?
查看>>
npm学习(十一)之package-lock.json
查看>>
npm安装 出现 npm ERR! code ETIMEDOUT npm ERR! syscall connect npm ERR! errno ETIMEDOUT npm ERR! 解决方法
查看>>
npm安装crypto-js 如何安装crypto-js, python爬虫安装加解密插件 找不到模块crypto-js python报错解决丢失crypto-js模块
查看>>
npm安装教程
查看>>
npm报错Cannot find module ‘webpack‘ Require stack
查看>>
npm报错Failed at the node-sass@4.14.1 postinstall script
查看>>
npm报错File to import not found or unreadable: @/assets/styles/global.scss.
查看>>
npm报错unable to access ‘https://github.com/sohee-lee7/Squire.git/‘
查看>>
npm版本过高问题
查看>>
npm的“--force“和“--legacy-peer-deps“参数
查看>>
npm的安装和更新---npm工作笔记002
查看>>
npm的常用配置项---npm工作笔记004
查看>>
npm的问题:config global `--global`, `--local` are deprecated. Use `--location=global` instead 的解决办法
查看>>
npm编译报错You may need an additional loader to handle the result of these loaders
查看>>
npm设置淘宝镜像、升级等
查看>>
npm设置源地址,npm官方地址
查看>>