C++中static要点总结

来源:互联网 发布:sql注入攻击步骤 编辑:程序博客网 时间:2024/05/21 19:42

C++中static要点总结

1、静态成员的提出是为了解决数据共享的问题。

2、因为静态成员函数是属于类的一部分,而不是某个对象的一部分,因此静态成员函数没有this指针,this指针是用于指向某个对象的。又因为静态成员函数没有this指针,因此在静态成员函数中不能直接调用非静态成员,因为非静态成员都是通过指向对象的this指针隐式或显式调用的。
在静态成员函数的实现中不能直接引用类中说明的非静态成员,可以引用类中说明的静态成员。如果静态成员函数中要引用非静态成员时,可通过对象来引用。

3、引用静态数据成员时,采用如下格式:
         <类名>::<静态成员名>
    如果静态数据成员的访问权限允许的话(即public的成员),可在程序中,按上述格式来引用静态数据成员。
也可以通过对象引用。

4、

静态成员函数不能即是static,又是const。因为:
When you apply the const qualifier to a non-static member function, it affects the this pointer. For a const-qualified member function of class C, the this pointer is of type C const*, whereas for a member function that is not const-qualified, the this pointer is of type C*.
A static member function does not have a this pointer (such a function is not called on a particular instance of a class), so const qualification of a static member function doesn't make any sense.

就是说const关键字是修饰this的,但是一旦使用了static关键字,this便与这个函数没有关系了,这样const便不能再修饰这个函数了。


与C相比,C中的用法:

1、一般情况下,对于局部变量是存放在栈区的,并且局部变量的生命周期在该语句块执行结束时便结束了。但是如果用static进行修饰的话,该变量便存放在静态数据区,其生命周期一直持续到整个程序执行结束。

2、修饰全局变量或函数,是它们的作用域仅限于本原文件。

0 0
原创粉丝点击