C++ 静态对象

Static in C++

Two basic meanings

Static Storage

--allocated once at a fixed address

Visibility of a name

--internal linkage

Don’t use static except inside functions and classes.

Uses of “static” in C++

Static free functions—-deprecated弃用

Static globle variables—-deprecated弃用

Static local variables—-Persistent storage持久存储

Static member variables—-Shared by all instances所有对象共享

Static member functions—-Shared by all instances, can only access static member variables所有对象共享,只能访问静态变量或静态函数

Static inside functions

Value is remembered for entire program

Initialization occurs only once

Static applied to objects…

Constructors are called before main() is entered

--Constructor called at-most once
--main() is no longer the first function called

--The constructor arguments must be satisfied

Destructors called when

--main() exited
--exited is called

–Compiler assures LIFO order of destructors

Can we apply static to members?

Static means

--Hidden(now usually use public,protected,private)

--Persistant

Hidden: A static member is a member

--Obeys usual access rules

Persistant: Independent of instances
假设有一个类:

class A{
 A(int,int);
 ~A();
 ...
}
void f(){
 static A a(6,6);
 ...
}

对象 a 的初始化发生在第一次进f() 函数的时候,空间在全局变量区,在编译(链接)的时候分配空间。
(而全局变量的构造发生在程序运行的时候,在main()之前)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值