A class member declared static is a single instance of that member shared by all instances of this class (that’s why it is sometimes termed a class variable, as opposed to object variable). This feature has many uses: for instance, in order to create a file lock, one can use a static bool class member. An object trying to access this file has to check first whether the static (i.e., shared) flag is false. If it is, the object turns the flag on and processes the file safely, since other objects will now find that the flag is now on, and hence — they cannot access the file. When the object processing the file is done, it has to turn off the flag, enabling another object to access it. How is a static member created?

class fileProc {
 FILE *p;
 static bool isLocked; //only a declaration; see definition below...
 public:
 bool isLocked () const {return isLocked; }
};//somewhere outside the class definition:

bool fileProc::isLocked; 
//definition; initialized to 'false' by default. Note: no 'static' here

定义一个function object来比较两个string的长度,从而使sort()利用此function object可以对container<string>进行排序。自写的function object的方式为定义struct并继承unary_function or binary_function。

#include <functional>
struct shorter_string : public binary_function<string,string,bool>
{
bool operator()(string a,string b)
{
return a.length()>b.length();
}
};
sort(iter_begin,iter_end,shorter_string());

这样一来就可以对container<string>中的对象从长到短排序了。

在编写template函数时,出现iterator对象,必须采用如下格式声明iterator。

typename container::iterator iter=container.begin();

没有加typename使我调试了半天都不知道为啥错误,Essential C++上对于template中使用vector的iterator前边并没有加typename,汗…

部分编译器接受未加typename的iterator声明,但这种程序的可移植性差,不安全。

以下引子Effective STL(Scott Myers)

为了避免潜在的解析含糊(我将提供给你细节),你被要求
在依赖形式类型参数的类型名字之前使用typename。这样的类型被称为依赖类型,
一个例子将帮助阐明我所说的。假设你想为函数写一个模板,给定一个STL容器,
返回容器中的最后一个元素是否大于第一个元素。这是一种方法:

template<typename C>
bool lastGreaterThanFirst(const C& container)
{
if (container.empty()) return false;
typename C::const_iterator begin(container, begin());

typename C::const_ierator end(container.end());

return *--end > *begin;
}

在这个例子里,局部变量begin和end的类型是C::const_iterator。const_iterator是依赖
形式类型参数C的一种类型。因为C::const_iterator是一种依赖类型,你被要求在它之前放上
typename这个词。(一些编译器错误地接受没有typename的代码,但这样的代码不可移植。)