友元
相关知识点:
- 私有成员对于类外部的所有程序部分而言都是隐藏的,访问它们需要调用一个公共成员函数,但有时也可能会需要创建该规则的一项例外。
- 友元函数是一个不属于类成员的函数,但它可以访问该类的私有成员。换句话说,友元函数被视为好像是该类的一个成员。友元函数可以是常规的独立函数,也可以是其他类的成员。实际上,整个类都可以声明为另一个类的友元。
- 类的友元函数是定义在类外部,但有权访问类的所有私有(
private
)成员和保护(protected
)成员。尽管友元函数的原型有在类的定义中出现过,但是友元函数并不是成员函数。 - 为了使一个函数或类成为另一个类的友元,必须由授予它访问权限的类来声明。类保留了它们的朋友的 “名单”,只有名字出现在列表中的外部函数或类才被授予访问权限。通过将关键字 friend 放置在函数的原型之前,即可将函数声明为友元。
- 友元是一种破坏数据隐蔽和封装的机制,这是它的用处也是它的坏处。应该尽量避免使用友元。
友元的性质:
- 友元关系是不能传递的,如A是B的友元,B是C的友元,但A不是C的友元
- 友元关系是单向的,A是B的友元,A可以访问B的私有属性,反之不成立
- 友元关系是不被继承的,A是B的友元,但A的派生类不是B的友元
友元函数的一般格式如下:
friend <return type><function name> (<parameter type list>);
代码涉及内容:
友元关系
三种友元:
普通函数(非成员函数);
类;
类的成员函数;
1 |
|
参考链接:
static 类成员
相关知识点:
- static类成员不像普通的类数据成员,
static
类数据成员独立于一切类对象处在。static
类数据成员是与类关联的,但不与该类定义的对象有任何关系。即static
不会像普通类数据成员一样每一个类对象都有一份,全部类对象是共享一个static
类成员的。 static
修饰的变量先于对象存在,所以static
修饰的变量要在类外初始化(除了静态常量整型可以在类内初始化外)。因为static
是所有对象共享的变量,必须要比对象先存在。- 由于
static
修饰的类成员属于类,不属于对象,因此static
类成员函数是没有this指针的,this
指针是指向本对象的指针。正因为没有this
指针,所以static
类成员函数不能访问非static
的类成员,只能访问static
修饰的类成员。
静态成员变量特性:
- 静态成员变量属于整个类所有
- 静态成员变量的生命期不依赖于任何对象,为程序的生命周期
- 可以通过类名直接访问公有静态成员变量
- 所有对象共享类的静态成员变量
- 可以通过对象名访问公有静态成员变量
- 静态成员变量需要在类外单独分配空间
- 静态成员变量在程序内部位于全局数据区 (
Type className::VarName = value
)
类的成员函数有如下特性:
- 静态成员函数是类的一个特殊的成员函数
- 静态成员函数属于整个类所有,没有
this
指针 - 静态成员函数只能直接访问静态成员变量和静态成员函数
- 可以通过类名直接访问类的公有静态成员函数
- 可以通过对象名访问类的公有静态成员函数
- 定义静态成员函数,直接使用
static
关键字修饰即可
好处:
用static修饰的成员变量在对象中是不占内存的,因为他不是跟对象一起在堆或者栈中生成,用static
修饰的变量在静态存储区生成的。所以用static
修饰一方面的好处是可以节省对象的内存空间。
代码涉及内容:
- 使用类的
static
成员的优点 - 定义
static
成员 - 使用类的s
tatic
成员 static
成员函数static
数据成员
1 |
|