The static members and constant objects of the class in C++
1.Xh file :
#ifndef X_H_INCLUDED
#define X_H_INCLUDED
class CX
{
public:
static int CXCount;
CX();
~CX();
};
#endif // X_H_INCLUDED
2. CX.cpp (implementation file of the class)
#include<iostream>
#include "X.h"
using namespace std;
int CX::CXCount=0;
CX::CX()
{
CXCount++;
cout<<"新建一个CX对象"<<endl;
cout<<"当前CX对象个数:"<<CXCount<<endl;
};
CX::~CX()
{
CXCount--;
cout<<"释放一个CX对象"<<endl;
cout<<"当前CX对象个数:"<<CXCount<<endl;
}
3.main.cpp
#include "X.h"
int main()
{
CX a,b,c;
CX*p1=new CX();
CX*p2=new CX();
delete p1;
delete p2;
return 0;
}
operation result:
新建一个CX对象
当前CX对象个数:1
新建一个CX对象
当前CX对象个数:2
新建一个CX对象
当前CX对象个数:3
新建一个CX对象
当前CX对象个数:4
新建一个CX对象
当前CX对象个数:5
释放一个CX对象
当前CX对象个数:4
释放一个CX对象
当前CX对象个数:3
释放一个CX对象
当前CX对象个数:2
释放一个CX对象
当前CX对象个数:1
释放一个CX对象
当前CX对象个数:0
Note: Static members are not attached to an object!
5. Constant object: use const to limit the changes of data members!
#include<iostream>
using namespace std;
class A
{
int m_a;
public:
A(int a):m_a(a){
}
void setA(int a){
m_a=a;}
int getA()const{
return m_a;}
};
int main()
{
const A a(100);
a.setA(20);//注意!此处编译未通过!数据成员一旦赋值便不能再修改!
return 0;
}