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

来源:互联网 发布:辛格尔软件 编辑:程序博客网 时间:2024/05/28 11:29

#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