静态对象是否调用构造函数?

#include <iostream>
 using namespace std;

 class A
 {
 public:
     A() { cout << "A's Constructor Called " << endl;  }
 };

 class B
 {
     static A a;
 public:
     B() { cout << "B's Constructor Called " << endl; }
 };

 int main()
 {
     B b;
     return 0;
 }


输出:

B's Constructor Called

解释:上面的程序只是调用了B的构造函数,没有调用A的构造函数。因为静态成员变量只是在类中声明,没有定义。静态成员变量必须在类外使用作用域标识符显式定义。 
如果我们没有显式定义静态成员变量a,就试图访问它,编译会出错,比如下面的程序编译出错:

#include <iostream>
 using namespace std;


 class A
 {
     int x;
 public:
     A() { cout << "A's constructor called " << endl;  }
 };


 class B
 {
     static A a;
 public:
     B() { cout << "B's constructor called " << endl; }
     static A getA() { return a; }
 };


 int main()
 {
     B b;
     A a = b.getA();
     return 0;
 }


输出:

Compiler Error: undefined reference to `B::a

如果我们加上a的定义,那么上面的程序可以正常运行, 
注意:如果A是个空类,没有数据成员x,则就算B中的a未定义也还是能运行成功的,即可以访问A。

#include <iostream>
 using namespace std;

 class A
 {
     int x;
 public:
     A() { cout << "A's constructor called " << endl;  }
 };

 class B
 {
     static A a;
 public:
     B() { cout << "B's constructor called " << endl; }
     static A getA() { return a; }
 };

 A B::a;  // definition of a

 int main()
 {
     B b1, b2, b3;
     A a = b1.getA();

     return 0;
 }

输出:

A's constructor called 
B's constructor called 
B's constructor called 
B's constructor called

上面的程序调用B的构造函数3次,但是只调用A的构造函数一次,因为静态成员变量被所有对象共享,这也是它被称为类变量的原因。同时,静态成员变量也可以通过类名直接访问,比如下面的程序没有通过任何类对象访问,只是通过类访问a。

int main()
 {
     // static member 'a' is accessed without any object of B
     A a = B::getA();

     return 0;
 }

输出:

A's constructor called

【出处】http://www.cnblogs.com/lanxuezaipiao/p/4148155.html


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值