Static data members in C++
Predict the output of following C++ program:
1 #include <iostream>
2 using namespace std;
3
4 class A
5 {
6 public:
7 A() { cout << "A's Constructor Called " << endl; }
8 };
9
10 class B
11 {
12 static A a;
13 public:
14 B() { cout << "B's Constructor Called " << endl; }
15 };
16
17 int main()
18 {
19 B b;
20 return 0;
21 }
Output:
B's Constructor Called
The above program calls only B’s constructor, it doesn’t call A’s constructor.
The reason for this is simple, static members are only declared in class declaration, not defined. They must be explicitly defined outside the class using scope resolution operator.
If we try to access static member ‘a’ without explicit definition of it, we will get compilation error. For example, following program fails in compilation.
1 #include <iostream>
2 using namespace std;
3
4 class A
5 {
6 int x;
7 public:
8 A()
9 {
10 cout << "A's constructor called " << endl;
11 }
12 };
13
14 class B
15 {
16 static A a;
17 public:
18 B()
19 {
20 cout << "B's constructor called " << endl;
21 }
22 static A getA()
23 {
24 return a;
25 }
26 };
27
28 int main()
29 {
30 B b;
31 A a = b.getA();
32 return 0;
33 }
Output:
Compiler Error: undefined reference to `B::a'
If we add definition of a, the program will works fine and will call A’s constructor. See the following program.
1 #include <iostream>
2 using namespace std;
3
4 class A
5 {
6 int x;
7 public:
8 A()
9 {
10 cout << "A's constructor called " << endl;
11 }
12 };
13
14 class B
15 {
16 static A a;
17 public:
18 B()
19 {
20 cout << "B's constructor called " << endl;
21 }
22 static A getA()
23 {
24 return a;
25 }
26 };
27
28 A B::a; // definition of a
29
30 int main()
31 {
32 B b1, b2, b3;
33
34 A a = b1.getA();
35
36 return 0;
37 }
Output:
A's constructor called
B's constructor called
B's constructor called
B's constructor called
Note that the above program calls B’s constructor 3 times for 3 objects (b1, b2 and b3), but calls A’s constructor only once. The reason is, static members are shared among all objects. That is why they are also known as class members or class fields. Also, static members can be accessed without any object.
See the below program where static member ‘a’ is accessed without any object.
1 #include <iostream>
2 using namespace std;
3
4 class A
5 {
6 int x;
7 public:
8 A()
9 {
10 cout << "A's constructor called " << endl;
11 }
12 };
13
14 class B
15 {
16 static A a;
17 public:
18 B()
19 {
20 cout << "B's constructor called " << endl;
21 }
22 static A getA()
23 {
24 return a;
25 }
26 };
27
28 A B::a; // definition of a
29
30 int main()
31 {
32 // static member 'a' is accessed without any object of B
33 A a = B::getA();
34
35 return 0;
36 }
Output:
A's constructor called
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
转载请注明:http://www.cnblogs.com/iloveyouforever/
2013-11-26 09:05:13
Static data members in C++的更多相关文章
- Static Classes and Static Class Members
Static Classes and Static Class Members A static class is basically the same as a non-static class, ...
- Link static data in sql source control
You can link data that doesn't change very often to SQL Source Control. This lets you commit data ch ...
- c# Use Properties Instead of Accessible Data Members
advantage of properties: 1 properties can be used in data binding, public data member can not. 2 dat ...
- Simplest way to serve static data from outside the application server in a Java web application
tomcat service.xml <Context docBase="/path/to/images" path="/images" /> re ...
- [EffectiveC++]item22:Declare data members private
将成员变量隐藏在函数接口的背后,可以为“所有可能的实现”提供弹性, 假设我们有一个public成员变量,而我们最终取消了它,多少代码可能会被破坏呢?那是一个不可知的大量. protected成员变量就 ...
- 条款22:将成员变量声明为private(Declare data members private)
NOTE: 1.切记将成员变量声明为private.这可赋予客户访问数据的一致性 可细微划分访问控制 允诺约束条件获得保证,并提供class作者以充分的实现弹性. 2.protected 并不比pub ...
- Initialization of data members
In C++, class variables are initialized in the same order as they appear in the class declaration. C ...
- C++ essentials 之 static 关键字
extraction from The C++ Programming Language, 4th. edition, Bjarne Stroustrup If no initializer is s ...
- Data 语义学(1)
一.Data Member 的绑定(The binding of Data Member) extern float x; class Point3d { public: Point3d( float ...
随机推荐
- Sentinel-Go 源码系列(二)|初始化流程和责任链设计模式
上节中我们知道了 Sentinel-Go 大概能做什么事情,最简单的例子如何跑起来 其实我早就写好了本系列的第二篇,但迟迟没有发布,感觉光初始化流程显得有些单一,于是又补充了责任链模式,二合一,内容显 ...
- shiro session返回问题
/** * 3.会话管理器 */ public DefaultWebSessionManager sessionManager() { CustomSessionManager sessionMana ...
- 第一天 python入门 基础 “”“Hello World”和if-elif的使用、数据类型
(1)第一个程序"""Hello World" 实现python环境打印输出:Hello World 程序: print("Hello World&q ...
- storm提交拓扑报错processing getcomponentpendingprofileactions
storm提交新的拓扑,拓扑能提交成功,但是在UI界面查看时每个bolt报错Thrift.processing getComponentPendingProfileActions异常. 原因:stor ...
- Hi3516开发笔记(一):海思HI3516DV300芯片介绍,入手开发板以及Demo测试
前言 目前主流国产芯片为RV11XX.RK33XX.Hi35XX系列,本系列开启Hi3516系列的开发教程. Hi3516DV300芯片介绍 Hi3516DV300为专业行Smart IP ...
- 接口返回图片,前端生成临时url实现展示、下载效果
请求一个后端接口 返回一张图片(打印后发现是二进制流) 瞬间不开心了(为什么不能后端处理好再让前端调用呢) 不过丝毫不慌好吧 先说处理逻辑:首先要将获取到的数据转换,这边选择以blob形式进行转换 主 ...
- python实现直线检测
目录: (一)原理 (二)代码(标准霍夫线变换,统计概率霍夫线变换) (一)原理 1.霍夫变换(Hough Transform) 霍夫变换是图像处理中从图像中识别几何形状的基本方法之一,应用很广泛,也 ...
- [loj3032]馕
(直接贪心会导致分子和分母过大) 令$S_{i}=\sum_{j=1}^{L}V_{i,j}$(即其独吞整个馕的快乐度),对第$i$个人求出$n$个位置$x_{1},x_{2},...,x_{n-1} ...
- [loj2850]无进位加法
(似乎漏了一个数据范围,cf上的题面中还有$\sum L\le 3\cdot 10^{5}$) 考虑$a_{i}=2^{k_{i}}$时(不妨$k_{1}\ge k_{2}\ge ...\ge k_{ ...
- [cf516E]Drazil and His Happy Friends
令$d=\gcd(n,m)$,存在$x$和$y$使得$xn+i=ym+j$的充要条件是$i\equiv j(mod \ d)$,因此将$xd+i$(其中$0\le i<d$)作为一组,共有$d$ ...