static.cpp文件:
#include <iostream>
#include "employ1.h"
using namespace std;
int main()
{
cout << "Number of employee before instantiation is "
<< Employee::count << endl;
Employee *e1Ptr = new Employee( "Suanu", "Mary" );
Employee *e2Ptr = new Employee( "Jack", "Rose" );
cout << "Number of employee after instantiation is "
<< e1Ptr->count << endl;
cout << "/n/nEmployee1:"
<< e1Ptr ->getFirstName()
<< " " << e1Ptr ->getLastName()
<< "/nEmployee2:"
<< e2Ptr ->getFirstName()
<< " "
<< e2Ptr ->getLastName() << "/n/n";
delete e1Ptr;
e1Ptr = 0;
delete e2Ptr;
e2Ptr = 0;
cout << "Number of employee after deletion is "
<< Employee::count << endl;
system("pause");
return 0;
}
employ1.h文件:
#ifndef EMPLOY1_H
#define EMPLOY1_H
class Employee
{
public:
Employee( const char *, const char * );
~Employee();
const char *getFirstName() const;
const char *getLastName() const;
static int getCount;
private:
char *fristName;
char *lastName;
int count;
};
#endif
employ1.cpp文件:
#include <iostream>
#include <cstring>
#include <cassert>
#include "employ1.h"
using namespace std;
int Employee::count = 0;
int Employee::getCount()
{
return count;
}
Employee::Employee( const char *first, const char *last )
{
firstName = new char( strlen( first ) + 1 );
assert( firstName != 0 )
strcpy( firstName, first );
lastName = new char( strlen( last ) + 1 );
assert( lastName != 0 )
strcpy( lastName, last );
++count;
cout << "Employee construct for " << firstName
<< '' << lastName << "called." << endl;
}
Employee::~Employee()
{
cout << "~Employee() called for " << firstName << '' << lastName << endl;
delete[] firstName;
delete[] lastName;
--count;
}
const char *Employee::firstName() const
{
return fistName;
}
const char *Employee::lastName() const
{
return lastName;
}
软件工程知识:有些公司的软件工程标准中,明确规定所有表态成员函数只能调用类名句柄,不能调用对象句柄。
常见编程错误:在静态成员函数中引用this指针是语法错误。
常见编程错误:将静态成员函数声明为常量是语法错误。
软件工程知识:即使类对象尚未初始化类的静态数据成员和成员函数也可以已经存在并可使用。
良好编程习惯:删除动态分配内存后,将指向该内存的指针设置为指向0,以切断指针与前面已分配内丰存的连接。
注意,Employee的构造函数使用了assert(断言)。assert类宏在Cassert头文件中定义,用以测试条件值。如果表达式的值为false,assert就会发出错误信息,并调用abort函数(在常用工具程序头文件<cstdlib>中)中止程序执行。这是个有用的调试工具,可以测试变量是否有正确值。注意,函数abort不运行任何析构函数即可中止程序执行。
在这个程序中,assert用于确定new操作符能否满足动态分配内存的请求。例如,在Employee构造函数中,语句(也称为断言):
assert( firstName != 0 );
用于测试指针 firstName,确定其是否不等于0。如果上述assert中的条件为true,程序将继续执行,不补中断。如果上述assert中的条件为false,程序就会打印出一条错误信息,包括行号、测试条件和assert所在的文件名,然后程序中止。程序员可以从这个代码中找出错误。
assert不一定要在调试完成后删除。程序不再用assert进行调试时,只须在程序文件开头(通常可以在编译器选项中指定)插入语句
#define NDEEUG
这时预处理程序会忽略所有断言,无须程序员手工删除各条断言。