C++中的静态数据成员

静态数据成员是使用静态关键字声明的类成员。静态成员具有某些特殊特性。这些是:

null
  • 只为整个类创建该成员的一个副本,并由该类的所有对象共享,无论创建了多少个对象。
  • 它是在创建此类的任何对象之前初始化的,甚至在main启动之前。
  • 它只在类中可见,但它的生命周期是整个程序的生命周期

语法

静态数据类型数据成员名称;

C++

#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”,就会出现编译错误。例如,以下程序编译失败。

C++

#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的构造函数。请参阅以下程序。

C++

#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 calledB's constructor calledB's constructor calledB's constructor called

请注意,上面的程序为3个对象(b1、b2和b3)调用了B的构造函数3次,但只调用了A的构造函数一次。原因是, 静态成员在所有对象之间共享。这就是为什么它们也称为类成员或类字段 而且 静态成员可以在没有任何对象的情况下访问 ,请参阅下面的程序,其中访问静态成员“a”时不使用任何对象。

C++

#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()
{
// static member 'a' is accessed without any object of B
A a = B::getA();
return 0;
}


输出:

A's constructor called

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写评论

© 版权声明
THE END
喜欢就支持一下吧
点赞6 分享