文档介绍:C++程序设计
第6章类和对象
类和对象
类的声明和定义
构造函数和析构函数
隐含的this指针
静态成员
友元
运算符重载
复杂形式的对象
指向类成员的指针
对象的作用域和生存期
本章小结
第6章类和对象
类和对象
一些基本概念
对象:对象是其自身所具有的状态特征及可以对这些状态施加的操作结合在一起所构成的独立实体。
类:对一组客观事物(即对象)的抽象,它将该组对象所具有的共同特征(结构/属性特征和行为/功能特征)集中起来,以说明该组对象的能力和性质。
封装与信息隐藏:就是把对象的属性和行为结合成一个独立的系统单位,并尽可能地隐藏对象的一些内部实现细节。
类的声明与定义
类的声明:指将一个类的类型名称告诉编译器,声明不带有细节信息,一般形式如下:
class <类名>; // 类的声明
例如:
class Clock; // 类的声明
class <类名> {
public:
<public数据成员或成员函数声明>
protected:
<protected数据成员或成员函数声明>
private:
<private数据成员或成员函数声明>
};
类的声明与定义
类的定义:指将类细节信息提供给编译器,类的定义必须列出类的所有成员,包括数据成员和函数成员。类的定义格式如下:
类的声明与定义
图6-1 类定义示意图
类的声明与定义
class是关键字,表示定义一个类;
pubic/protected/private是类外代码存取访问权限控制关键字。
数据成员,表示该类对象包含的数据,描述类对象的属性特征;成员函数,表示对数据成员进行操作或处理的过程,用函数形式来实现,描述类对象的行为特征;
类的实现部分给出类成员函数的具体实现,可以放在类定义中,也可放在类定义外。格式如下:
<函数类型> <类名>::<成员函数名> (<参数表>) {
<函数体>
}
说明:
【例 】定义日期(Tdate)类,该类对象可以代表普通的日期。注意:将日期(Tdate)类的定义部分和实现部分放在一起。
类的声明与定义
// 日期类的定义,类的定义与实现部分放在一起
#include <iostream>
using namespace std;
class Tdate {
public:
void setDate(int y, int m, int d) {
year = y; month = m; day = d;
}
int isLeapYear( ) {
return ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0));
}
void print( ) {
cout << year << ", " << month << ", " << day << endl;
}
private:
int year, month, day; };
【】重新定义日期(Tdate)类,将日期(Tdate)类的定义和实现独立存放。
类的声明与定义
//
// 日期类的定义
class Tdate{
public:
void setDate(int y, int m, int d);
int isLeapYear( );
void print( );
private:
int year, month, day;
};
//
// 日期类的实现
#include <iostream>
#include "tdate h"
using namespace std;
void Tdate::setDate(int y, int m, int d) {
year = y; month = m; day = d;
}
int Tdate::isLeapYear( ) {
return ((year%4 == 0 && year % 100 != 0) || (year % 400 == 0));
}
void Tdate::print( ) {
cout << year << ", " << month << ", " << day << endl;
}
类的声明与定义