对象的使用
1. static关键字
(1)static成员
1) 对于特定类型的全体对象而言,有时候可能需要访问一个全局的变量。
2) 如果我们用全局变量会破坏数据的封装,一般的用户代码都可以修改这个全局变量,这时我们可以用类的静态成员来解决这个问题。
3) 非static数据成员存在于类类型的每个对象中,static数据成员独立该类的任意对象存在,它是与类关联的对象,不与类对象关联。
A. static成员需要在类定义体外进行初始化与定义
B. static成员的优点
Ø static成员的名字是在类的作用域中,因此可以避免与其它类成员或全局对象名字冲突
Ø 可以实现封装,static成员可以是私有的,而全局对象不可以
Ø 阅读程序容易看出static成员与某个类相关联,这种可见性可以清晰地反映程序员的意图
C. static const成员的使用——整型static const成员可以在类定义体中初始化,该成员可以不在类体外进行定义。
(2)static成员函数
A. static成员函数没有this指针
B. 非静态成员函数可以访问静态成员
C. 静态成员函数不可以访问非静态成员
(3)static总结
在C语言中,static修饰的变量保存在数据区的静态数据区,未初始化默认初始化未0;static既可以修饰变量,也可以修饰函数;
a) 修饰局部变量:静态局部变量延长变量的生命周期直至程序运行结束才释放;
b) 修饰全局变量:该全局变量只能在本文件可见,其它文件不可见;
c) 修饰函数:该函数只能在本文件内调用,不能在其他文件中调用。
在C++语言中,static既可以修饰成员,也可以修饰成员函数;
a) 修饰成员:修饰的变量只能在类外初始化,只有整型static const成员,可以在类内初始化,static修饰的变量置于private中时,类外不能访问;
b) 修饰成员函数:修饰的函数属于类,不属于某个对象,可以被共享。
2. const关键字
1) 在C语言中,const只能修饰变量,该变量称为只读变量,不能通过变量名修改变量值,但可通过变量空间修改;一般用来修饰函数形参,避免在函数实现中修改实参的值,便于调试。
2) 在C++语言中,const即可修饰成员,也可修饰成员函数;
a) 修饰成员:必须在成员列表中初始化;
b) 修饰成员函数:不会修改对象的状态;只能访问成员数据的值,不能修改,修饰成员指针,成员指针指向的数据可变,但指针指向的空间不能变。
const对象不能调用非const成员函数。
3. mutable关键字
用mutable修饰的数据成员即使在const对象或在成员函数中都可以被修改。
示例:
[String.h]
#ifndef_STRING_H_
#define_STRING_H_
class String
{
public:
String();
~String();
//static int MAX_LEN;//类外能够访问到
//static void Display();//static成员函数可以访问静态对象,
//静态成员函数不可以访问非静态成员
//静态成员函数可以访问静态成员
//非静态成员函数可以访问静态静态成员
void Display() const;//const成员函数
String(char *str);
String(const String& other);
String& operator = (const String&other);
private:
char *str_;
//mutable char *str_;//通过const对象或const成员函数中可修改其值
static int MAX_LEN;//只能在类外初始化,不能在类外访问,若置于public中可以访问
//static const int MAX_LEN1 = 1024;//整型staticconst变量可在类内初始化
};
#endif
[String.cpp]
#include<iostream>
#include<string.h>
#include"String.h"
using namespacestd;
String::String()
{
str_ = new char('\0');
cout << "default constructorString" << endl;
}
String::~String()
{
cout << "destroy String"<< endl;
delete [] str_;
}
String::String(char*str)
{
cout << "constructorString" << endl;
int len = strlen(str) + 1;
str_ = new char[len];
memset(str_, 0, len);
strcpy(str_, str);
}
voidString::Display() const
{
//str_++;//报错,const成员函数只能访问数据的值,不能修改,修饰指针时,指针的的数据可变,但指针地址不能改变
//当str_修饰为mutable时,str_++;不会报错
(*str_)++;//不报错
cout << str_ << endl;
}
String::String(constString& other)
{
int len = strlen(other.str_) + 1;
str_ = new char[len];
memset(str_, 0, len);
strcpy(str_, other.str_);
}
String&String::operator = (const String& other)
{
if(this == &other)
{
return *this;
}
int len = strlen(other.str_) + 1;
delete [] str_;
str_ = new char[len];
memset(str_, 0, len);
strcpy(str_, other.str_);
}