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++的更多相关文章

  1. Static Classes and Static Class Members

    Static Classes and Static Class Members A static class is basically the same as a non-static class, ...

  2. 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 ...

  3. 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 ...

  4. 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 ...

  5. [EffectiveC++]item22:Declare data members private

    将成员变量隐藏在函数接口的背后,可以为“所有可能的实现”提供弹性, 假设我们有一个public成员变量,而我们最终取消了它,多少代码可能会被破坏呢?那是一个不可知的大量. protected成员变量就 ...

  6. 条款22:将成员变量声明为private(Declare data members private)

    NOTE: 1.切记将成员变量声明为private.这可赋予客户访问数据的一致性 可细微划分访问控制 允诺约束条件获得保证,并提供class作者以充分的实现弹性. 2.protected 并不比pub ...

  7. Initialization of data members

    In C++, class variables are initialized in the same order as they appear in the class declaration. C ...

  8. C++ essentials 之 static 关键字

    extraction from The C++ Programming Language, 4th. edition, Bjarne Stroustrup If no initializer is s ...

  9. Data 语义学(1)

    一.Data Member 的绑定(The binding of Data Member) extern float x; class Point3d { public: Point3d( float ...

随机推荐

  1. ansible简介安装配置

    ansible简介 ansible是一款,自动化运维管理工具.顾名思义是用于批量去管理及安装服务及批量管理主机. ansible与saltstack对比 ansible优点:配置简单,部署容易除主管理 ...

  2. log4j日志集成

    一.介绍  Log4j是Apache的一个开放源代码项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台.文件.GUI组件.甚至是套接口服务 器.NT的事件记录器.UNIX Syslog ...

  3. PAT甲级1074 Reversing Linked List (25分)

    [程序思路] 先根据地址按顺序读入节点,入栈,当栈里的元素个数等于k时全部出栈,并按出栈顺序保存,最后若栈不为空,则全部出栈并按出栈的稀饭顺序保存,最后输出各节点 注意:输入的节点中有可能存在无用节点 ...

  4. 菜鸡的Java笔记 第三十 - java 异常的捕获及处理

    异常的捕获及处理        1.异常的产生分析以及所带来的影响        2.异常的处理的基本格式        3.异常的处理流程        4.异常的处理模式        5.自定义 ...

  5. 【Linux】解压分卷压缩的zip文件

    例如linux.zip.001, linux.zip.002, linux.zip.003. 1. cat linux.zip* > linux.zip #合并为一个zip包. 2. unzip ...

  6. [源码解析] PyTorch 分布式(8) -------- DistributedDataParallel之论文篇

    [源码解析] PyTorch 分布式(8) -------- DistributedDataParallel之论文篇 目录 [源码解析] PyTorch 分布式(8) -------- Distrib ...

  7. VS2013中using System.Windows.Forms;引用不成功

    命名空间"System"中不存在类型或命名空间名称"Windows" 项目右侧--解决资源管理器---引用---右键--添加引用---在.NET下拉框找---找 ...

  8. 测试平台系列(79) 编写Redis配置功能(下)

    大家好~我是米洛! 我正在从0到1打造一个开源的接口测试平台, 也在编写一套与之对应的完整教程,希望大家多多支持. 欢迎关注我的公众号测试开发坑货,获取最新文章教程! 回顾 上一节我们提出了优化Dao ...

  9. [loj3333]混合物

    假设选择的调味瓶为$k_{1}<k_{2}<...<k_{s}$,即判定是否存在正有理数解$\{x_{1},x_{2},...,x_{s}\}$,满足$$(\sum_{i=1}^{s ...

  10. [bzoj1107]驾驶考试

    转化题意,如果一个点k符合条件,当且仅当k能到达1和n考虑如果l和r($l<r$)符合条件,容易证明那么[l,r]的所有点都将会符合条件,因此答案是一个区间枚举答案区间[l,r],考虑如何判定答 ...