static修饰成员函数
#include "stdafx.h"
#include <iostream>
using namespace std;
#include <string>
#if 0
static 修饰成员函数,它的作用只有一个,用于管理static成员
static 修饰的成员函数,既属于类也属于对象,
但终究属于类 可以不用创建对象的情况下访问
也可以认为是School命名空间里的一个函数
static 修饰的成员函数,因为他属于类,所以它没有this指针,
不能访问非static数据成员及非static成员函数
非静态成员函数可以访问静态成员函数 而静态成员函数不能访问非静态成员函数
非静态成员函数可以访问静态数据成员 而静态成员函数不能访问非静态数据数据成员
因为 访问非静态成员函数 非静态数据成员的前提是需要有对象
而静态成员函数和静态数据成员可以在没有对象 只有类的情况下访问
#endif
class School
{
public:
string & getTower()
{
return tower;
}
static string & getlib() //static 修饰成员函数
{
return lib;
}
private:
string tower;
string lake;
static string lib;
};
string School::lib = "";
int _tmain(int argc, _TCHAR* argv[])
{
School::getlib() = "九阴真经";
School::getlib() += "+六脉神剑";
School cz, bn, blueshit;
cz.getTower() = "boyata";
bn.getTower() = "shuita";
blueshit.getTower() = "wajueta";
cz.getlib() += "+传智";
bn.getlib() += "+青鸟";
blueshit.getlib() += "+挖掘机";
cout << cz.getlib() << endl;
cout << bn.getlib() << endl;
cout << School::getlib() << endl;
return 0;
}
static修饰类成员,实现渲染树的模拟
#include "stdafx.h"
#include <iostream>
using namespace std;
class CCSprite
{
public:
CCSprite(int i) :data(i)
{
#if 0
if (head == NULL)
{
this->next = NULL;
head = this;
}
else
{
this->next = head->next;
head = this;
}
#endif
//与链表有所不同
this->next = head;
head = this;
}
static void traverseCCSprite()
{
CCSprite* ph = head;
while (ph != NULL)
{
cout << ph->data << endl;
ph = ph->next;
}
}
private:
int data;
CCSprite* next;
static CCSprite* head;
};
CCSprite* CCSprite::head = NULL;
int _tmain(int argc, _TCHAR* argv[])
{
CCSprite a(1), b(2), c(3);
for (int i = 100; i < 106; i++)
new CCSprite(i);
//栈上的和堆上的都可以连接到一起
//可以将数据合到一起进行统一管理
CCSprite::traverseCCSprite();
return 0;
}