#include <iostream>
class Test{
public:
explicit Test(); //explicit关键字用于抑制由构造函数定义的隐式转换
static int st;
int static sget();//staic 成员函数没有this指针,因此也不能被声明为const
Test &set(int m);
private:
//const static 变量可以在类定义体中初始化
const static int cst = 9;
const int ct;
};
int Test::st = 3;
//explicit关键字只能用于类内部的构造函数上,此处不用
Test::Test():ct(8){//const 变量在构造函数中初始化
//定义中加explicit关键字,但该文件并没实际应用到
}
int Test::sget() //static 函数定义不需要在加static
{
return st;
}
Test& Test::set(int m){
st = m;
return *this;
}
int main()
{
Test t;
//static 变量、函数可以用类直接调用
std::cout<<Test::st<<' '<<Test::sget()<<std::endl;
//set 返回类型为Test& 因此可以连续调用
std::cout<<t.set(21).sget()<<std::endl;
}
/**输出结果
3 3
21
**/
参考:
《C++ Primer》第12章 类