C++静态成员(2) - 静态数据成员

来源:互联网 发布:做网站java还是php 编辑:程序博客网 时间:2024/06/06 02:07

1. 静态成员的构造

参考下面程序输出:
#include <iostream>class A{public:    A() { std::cout << "A's Constructor Called" << std::endl;  }};class B{    static A a;public:    B() { std::cout << "B's Constructor Called" << std::endl; }};int main(){    B b;    return 0;}
输出:
B's Constructor Called

从上述结果可以看到,程序只调用了B的构造函数,而没有调用A的构造函数。原因很简单,静态成员仅仅在类声明的时候而声明,但是不会定义。它们必须在类的外边被显示地定义。

2. 静态成员的访问

如果访问这个没有被显式定义的静态成员'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的构造函数。

#include <iostream>class A{  int x;public:  A()  {    std::cout << "A's constructor called " << std::endl;  }};class B{  static A a;public:  B()  {    std::cout << "B's constructor called " << std::endl;  }  static A  getA()  {    return a;  }};A B::a; // 对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

注意:
1. A的构造函数先于B的构造函数被调用,因为它是静态成员。
2. 上述程序调用了3次B的构造函数,而只调用了1次A的构造函数。这是因为静态成员是在所有对象间共享的。这也是为何说它们都是类级别的或类作用域的。
3. 另外,静态成员可以不需要用任何对象来访问。下面例子中静态成员'a'不需要依靠任何对象进行访问.

#include <iostream>class A{    int x;public:    A() { std::cout << "A's constructor called " << std::endl;  }};class B{    static A a; // a的声明public:    B() { std::cout << "B's constructor called " << std::endl; }    static A getA() { return a; }};A B::a;  // a的定义int main(){    // 静态成员不需要依靠任何B的对象来访问。    A a = B::getA();    return 0;}
输出:
A's constructor called
0 0
原创粉丝点击