- /* objcount.cpp
-
*类的嵌套,此例可以跟踪程序在任何时候
-
*有多少该类型的对象
-
*/
-
#include <iostream>
-
-
using namespace std;
-
-
class TAnyClass {
-
private:
-
typedef int CLASS_COUNTER;
-
static CLASS_COUNTER ClassCount;
-
static int GetCount() { return ClassCount; }
-
public:
-
TAnyClass() { ClassCount++; }
-
~TAnyClass() { ClassCount --; }
-
static void ShowCount();
-
struct ClassStruct {
-
int x, y;
-
};
-
};
-
-
//Define static member
-
TAnyClass::CLASS_COUNTER TAnyClass::ClassCount;
-
TAnyClass globalObject;
-
-
int main()
-
{
-
cout << "On entry to program" << endl;
-
TAnyClass::ShowCount();
-
-
TAnyClass localObject;
-
cout << "After constructing one object" << endl;
-
TAnyClass::ShowCount();
-
-
TAnyClass objectA, objectB, objectC;
-
cout << "After constructing three objects" << endl;
-
TAnyClass::ShowCount();
-
-
TAnyClass * pointer = new TAnyClass;
-
cout << "After creating a dynamic object" << endl;
-
TAnyClass::ShowCount();
-
delete pointer;
-
cout << "After deleting the dynamic object" << endl;
-
TAnyClass::ShowCount();
-
-
//引用结构体
-
TAnyClass::ClassStruct structure;
-
structure.x = 1;
-
cout << "y == " << structure.y << "x == " << structure.x
-
<< endl;
-
-
return 0;
-
}
-
-
void TAnyClass::ShowCount()
-
{
-
cout << "Number of objects == " << TAnyClass::GetCount();
-
cout << endl;
-
}
类的内部嵌套定义 typedef
int CLASS_COUNTER
;还有一个示例结构体 struct ClassStruct
及静态类,静态变量不和对象捆绑使用,且不会接收this指针。。
一些不常用的关键字:
implicit:强制调用所需的类构造器,拒绝C++隐式转换成类型
mutable: 类内部函数声明对成员变量不修改时,如:int getvalue()const { counter ++; } 这时编译会报错,
此时在变量前加上此关键字,允许函数修改此单个变量。