1、static关键字作用
(1)函数体内static变量的作用范围为该函数体,不同于auto变量,该变量的内存只被分配一次(初始化一次),因此其值在下次调用时仍维持上次的值;
(2)在模块内的static全局变量可以被模块内所用函数访问,但不能被模块外其它函数访问;
(3)在模块内的static函数只可被这一模块内的其它函数调用,这个函数的使用范围被限制在声明它的模块内;
(4)在类中的static成员变量属于整个类所拥有,对类的所有对象只有一份拷贝;
(5)在类中的static成员函数属于整个类所拥有,这个函数不接收this指针,因而只能访问类的static成员变量。
2、const关键字作用
(1)欲阻止一个变量被改变,可以使用const关键字。在定义该const变量时,通常需要对它进行初始化,因为以后就没有机会再去改变它了;
(2)对指针来说,可以指定指针本身为const,也可以指定指针所指的数据为const,或二者同时指定为const;
(3)在一个函数声明中,const可以修饰形参,表明它是一个输入参数,在函数内部不能改变其值;
(4)对于类的成员函数,若指定其为const类型,则表明其是一个常函数,不能修改类的成员变量;
(5)对于类的成员函数,有时候必须指定其返回值为const类型,以使得其返回值不为“左值”。
例如:const classA operator*(const classA& a1,const classA& a2);
operator*的返回结果必须是一个const对象。
3、String类
class String
{
public:
String(const char *str=NULL);
String(const String &other);
~String(void);
String &operate=(const String &other);
private:
char *m_data;
};
String::String(const char *str)
{
if( str == NULL )
{
m_data = new char[1];
m_data[0] = '\0';
//*m_data = '\0';
}
else
{
m_data = new char[strlen(str)+1];
strcpy( m_data, str );
}
}
String::String(const String &other)
{
m_data = new char[strlen(other.m_data)+1];
strcpy(m_data, other.m_data );
}
//重载操作符=
String & String::operate=(const String &other)
{
if( this == &other )
return *this;
delete [] m_data;
m_data = new char[strlen(other.m_data)+1];
strcpy(m_data, other.m_data);
return *this;
}
String::~String(void)
{
delete [] m_data;
}