博客
关于我
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 Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>
No module named 'crispy_forms'等使用pycharm开发
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
查看>>
No new migrations found. Your system is up-to-date.
查看>>
No qualifying bean of type XXX found for dependency XXX.
查看>>
No resource identifier found for attribute 'srcCompat' in package的解决办法
查看>>
no session found for current thread
查看>>
No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
查看>>
NO.23 ZenTaoPHP目录结构
查看>>
NO32 网络层次及OSI7层模型--TCP三次握手四次断开--子网划分
查看>>
NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
查看>>
Node JS: < 一> 初识Node JS
查看>>
Node-RED中使用JSON数据建立web网站
查看>>
Node-RED中使用json节点解析JSON数据
查看>>