您的位置:首页 > 编程语言 > C语言/C++

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

2015-05-31 20:26 483 查看
#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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++