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

你可能感兴趣的文章
Oracle11G基本操作
查看>>
PayPal网站付款标准版(for PHP)
查看>>
Paystack Android SDK 集成与使用指南
查看>>
PC端编辑 但能在PC端模拟移动端预览的富文本编辑器
查看>>
Penetration Testing、Security Testing、Automation Testing
查看>>
php -- 魔术方法 之 判断属性是否存在或为空:__isset()
查看>>
php csv 导出
查看>>
php include和require
查看>>
php mysql优化方法_MySQL优化常用方法
查看>>
PHP OAuth 2.0 Server
查看>>
php odbc驱动,php常用ODBC函数集(详细)
查看>>
php openssl aes ecb,php openssl_encrypt AES-128-ECB iOS
查看>>
php paypal rest api,PayPal REST API指定网络配置文件PHP
查看>>
PHP pcntl_fork不能在web服务器中使用的变通方法
查看>>
php private ,public protected三者的区别
查看>>
php PSR规范
查看>>
php rand() 重复,array_rand()函数从另外一个数组中随机取得的一定数量的数组的元素是否会重复?...
查看>>
php redis(2)
查看>>
PHP Redis分布式锁
查看>>
PHP SOAP模块的使用方法:NON-WSDL模式
查看>>