Static members of a C++ class

We can define class members static using static keyword. When we declare a member of a class as static it means no matter how many objects of the class are created, there is only one copy of the static member.

A static member is shared by all objects of the class. All static data is initialized to zero when the first object is created, if no other initialization is present. We can‘t put it in the class definition but it can be initialized outside the class as done in the following example by redeclaring the static variable, using the scope resolution operator :: to identify which class it belongs to.

Let us try the following example to understand the concept of static data members:

#include <iostream>
 using namespace std;class Box{
   public:
      static int objectCount;
      // Constructor definition
      Box(double l=2.0, double b=2.0, double h=2.0)
      {
         cout <<"Constructor called." << endl;
         length = l;
         breadth = b;
         height = h;
         // Increase every time object is created
         objectCount++;
      }
      double Volume()
      {
         return length * breadth * height;
      }
   private:
      double length;     // Length of a box
      double breadth;    // Breadth of a box
      double height;     // Height of a box};// Initialize static member of class Boxint Box::objectCount = 0;int main(void){
   Box Box1(3.3, 1.2, 1.5);    // Declare box1
   Box Box2(8.5, 6.0, 2.0);    // Declare box2

   // Print total number of objects.
   cout << "Total objects: " << Box::objectCount << endl;

   return 0;}

When the above code is compiled and executed, it produces the following result:

Constructor called.Constructor called.Total objects: 2

Static Function Members:

By declaring a function member as static, you make it independent of any particular object of the class. A static member function can be called even if no objects of the class exist and the static functions are accessed using only the class name and the scope resolution operator ::.

A static member function can only access static data member, other static member functions and any other functions from outside the class.

Static member functions have a class scope and they do not have access to thethis pointer of the class. You could use a static member function to determine whether some objects of the class have been created or not.

Let us try the following example to understand the concept of static function members:

#include <iostream>
 using namespace std;class Box{
   public:
      static int objectCount;
      // Constructor definition
      Box(double l=2.0, double b=2.0, double h=2.0)
      {
         cout <<"Constructor called." << endl;
         length = l;
         breadth = b;
         height = h;
         // Increase every time object is created
         objectCount++;
      }
      double Volume()
      {
         return length * breadth * height;
      }
      static int getCount()
      {
         return objectCount;
      }
   private:
      double length;     // Length of a box
      double breadth;    // Breadth of a box
      double height;     // Height of a box};// Initialize static member of class Boxint Box::objectCount = 0;int main(void){
  
   // Print total number of objects before creating object.
   cout << "Inital Stage Count: " << Box::getCount() << endl;

   Box Box1(3.3, 1.2, 1.5);    // Declare box1
   Box Box2(8.5, 6.0, 2.0);    // Declare box2

   // Print total number of objects after creating object.
   cout << "Final Stage Count: " << Box::getCount() << endl;

   return 0;}

When the above code is compiled and executed, it produces the following result:

Inital Stage Count: 0Constructor called.Constructor called.Final Stage Count: 2
时间: 2024-11-05 12:25:33

Static members of a C++ class的相关文章

JavaScript Patterns 5.6 Static Members

Public Static Members // constructor var Gadget = function (price) { this.price = price; }; // a static method Gadget.isShiny = function () { // this always works var msg = "you bet"; // Checking if the static method is called by instance. if (t

C# - Static Members

A non-static class can contain static methods, fields, properties, or events. The static member is callable on a class even when no instance of the class has been created. The static member is always accessed by the class name, not the instance name.

学习 learning Java for android-import static

第一次写博客,好紧张. import static:可以把一个的静态成员导入到当前类中,而不导入其他成员.避免了常量接口的使用.比如说我们可以 import static java.lang.Math.*; // Import all static members from Math.这样我们就可以在当前类中直接使用PI啦,就不需要用Math.PI

static, readonly, const

static Use the static modifier to declare a static member, which belongs to the type itself rather than to a specific object. The static modifier can be used with classes, fields, methods, properties, operators, events, and constructors, but it canno

C++:关于class member声明为static的情况

2014.5.27 reference: C++ primer 5th, $7.6:Static Class Members TOPIC 1:一个类中的member(data member和function member)可以声明为static,需要申明为static的情况有一下原因: 1:使用的客观需要:需要某个member是associated with the class,not with individual objects(如银行class中的prime interest rate这个

java各公司笔试题集1

IBM笔试题 注:IBM笔试题一小时之内完成,题目全部用英文描述,这里用中文表述 一.名词解释 1.Eclipse 2.J2EE 3.EJB 4.Ajax 5.Web service 二.找出以下代码问题 public class test{ public void print(String str){ char[] s=str: } } public class a{ public static void main(String [] args){ puts() } } 三.写出以下输出 pu

STS清理

图中插入代码如下,文件名随意最好见名知意 Add 'this' qualifier to unqualified field accesses Add 'this' qualifier to unqualified method accesses Qualify accesses to static fields with declaring class Qualify accesses to static methods with declaring class Change non stat

Swift中编写单例的正确方式

Swift中编写单例的正确方式 2015-12-07 10:23 编辑: yunpeng.hu 分类:Swift 来源:CocoaChina翻译活动 14 10647 Objective-CSwift单例 招聘信息: Cocos2d-x 工程师 cocos2dx手游客户端主程 wp开发 iOS开发工程师 iOS软件工程师 iOS研发工程师 iOS讲师 iOS开发工程师 iOS高级开发工程师 iOS 高级软件工程师 iOS高级开发工程师 本文由CocoaChina译者leon(社区ID)翻译自kr

深入理解javascript闭包【整理】

原文链接:http://www.cn-cuckoo.com/2007/08/01/understand-javascript-closures-72.html 英文原文:http://www.jibbering.com/faq/faq_notes/closures.html 要成为高级 JavaScript 程序员,就必须理解闭包. 本文结合 ECMA 262 规范详解了闭包的内部工作机制,让 JavaScript 编程人员对闭包的理解从"嵌套的函数"深入到"标识符解析.执行