Query on Static member variables of a class

时间:2015-08-07 02:20:25

标签: c++

I have few classes defined in this fashion :

class CSocket {
    protected:
        int m_SockWorking;
        int InitSocket();
        void CleanSocket();
}

class CSocketClient : public CSocket {
    public:
        CSocketClient();
        int InitClient();
}

class CApi {
    static CSocketClient c1;
    public:
        // other methods defined 
}

Now, in the main routine I create two objects of class CApi. I know that for static member variables there exists only one copy per class. But, how can I access m_SockWorking variable for CSocketClient member variable? Will there be two copies of that non static member variable for the two objects? Can somebody please explain?

2 个答案:

答案 0 :(得分:3)

All CApi classes will share a single static CSocketClient variable.

m_SockWorking is a protected member of CSocket which is inheirited by CSocketClient this makes it a private variable inside the context of CApi and your application. So you can access it through the use of accessor and mutator functions.

Each CSocketClient has its own m_SockWorking variable. Since all CApi all share the same CSocketClient class, they all share the same m_SockWorking variable.

CSocket.h

class CSocket {
  protected:
    int m_SockWorking;
    int InitSocket();
    void CleanSocket();
  public:
    void setSocket(int val){ m_SockWorking = val; } /* added these functions to show how to accessing m_SockWorking can be done */
    int getSocket() const { return m_SockWorking; }
};

class CSocketClient : public CSocket {
  public:
    CSocketClient();
    int InitClient();

};

class CApi {
  static CSocketClient c1;
  public:
    // other methods defined 
};

main.cc

#include "CSocket.h"
#include <iostream>
using std::cout;
using std::endl;

int main(){
  CApi a, b;
  CSocketClient c2;
  a.c1.setSocket(0); /* sets static c1 m_SockWorking variable to 0 */
  cout << b.c1.getSocket() << endl; /* will print 0 since c1 is a static variable */
  c2.setSocket(1); /* set c2 m_SockWorking to 1 */
  cout << c2.getSocket() << endl; /* will print 1 */
  cout << a.c1.getSocket() << endl; /* will print 0 */
}

Output

0
1
1

答案 1 :(得分:0)

是,对象c1是唯一的,因此,c1中的所有数据成员对于CApi都是唯一的。

这样可能不那么令人困惑:

静态对象c1是一个独立的&amp; “CLASS”CApi的唯一对象,可由CApi的对象访问。它属于类,不属于CApi的任何对象;它不是CApi对象的共享部分。