- 1、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。。
- 2、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载。
- 3、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
- 4、该文档为VIP文档,如果想要下载,成为VIP会员后,下载免费。
- 5、成为VIP后,下载本文档将扣除1次下载权益。下载后,不支持退款、换文档。如有疑问请联系我们。
- 6、成为VIP后,您将拥有八大权益,权益包括:VIP文档下载权益、阅读免打扰、文档格式转换、高级专利检索、专属身份标志、高级客服、多端互通、版权登记。
- 7、VIP文档为合作方或网友上传,每下载1次, 网站将根据用户上传文档的质量评分、类型等,对文档贡献者给予高额补贴、流量扶持。如果你也想贡献VIP文档。上传文档
查看更多
CPP程序设计第08课时教案
课 时 教 案
周 次 第4周第2次课 课题 类(一) 授课类型 理论课( √ )、实践课( √ )、实习( ) 时间设计 授
课
内
容
与
教
学
设
计 类的定义和使用
1. 结构与类的比较
程序范例:
定义一个日期类型,有年、月、日三个部分。并使用它。
//使用结构体,P253
#include iostream
#include iomanip
using namespace std;
struct Date
{
int year;
int month;
int day;
};
void print(Date);
bool isLeapYear(Date);
int main()
{
Date d;
d.year = 2011;
d.month = 1;
d.day = 12;
if(isLeapYear(d))
print(d);
print(d);
}
void print(Date d)
{
cout.fill(0);
coutsetw(4)d.year-setw(2)d.month-setw(2)d.dayendl;
cout.fill( );
}
bool isLeapYear(Date d)
{
return (d.year % 4 == 0 d.year % 100 != 0) || (d.year % 400 == 0);
}
结构体不利于程序代码的重用,为了提高代码的重用性,可以使用类来定义日期类型。
//使用类,见P255
#include iostream
#include iomanip
using namespace std;
class Date
{
int year;
int month;
int day;
public:
void set(int y,int m,int d);
void print();
bool isLeapYear();
};
int main()
{
Date d;
d.set(2011,1,12);
if(d.isLeapYear())
coutLeap Year:;
d.print();
}
void Date::set(int y,int m,int d)
{
year = y;month = m;day = d;
}
void Date::print()
{
cout.fill(0);
coutsetw(4)year-setw(2)month-setw(2)dayendl;
cout.fill( );
}
bool Date::isLeapYear()
{
return (year % 4 == 0 year % 100 != 0) || (year % 400 == 0);
}
讲解新知识点:
类的定义:
class 类名
{
数据成员定义;
访问权限符:
成员函数声明/定义;
}
数据成员是类的数据组成部分,其定义类似于变量的定义(数据类型 变量名)。
访问权限符:public、private、pretected等。
成员函数是类的操作,是类所具有的功能。
成员函数的定义可以在类中,也可以在类外。在类外实现时需要加“类名::”修饰。成员函数是从属于类的,不能独立存在。
对象:是类的实例,类似于某一类型的变量。通过对象可以调用类的函数,调用方式是:对象名.函数名()。
成员函数
成员函数的定义可以在类中,也可以在类外。
当定义了对象指针时,通过对象指针调用函数的方式是:
指针名-函数名();或者:(*指针名).函数名();
如:
#include iostream
#include iomanip
using namespace std;
class Date
{
int year;
int month;
int day;
public:
void set(int y,int m,int d);
void print();
bool isLeapYear();
};
int main()
{
Date* pd = new Date;
pd-set(2011,1,12);
if((*pd).isLeapYear())
coutLeap Year:;
(*pd).print();
}
void Date::set(int y,int m,int d)
{
year = y;month = m;day = d;
}
void Date::print()
{
cout.fill(0);
coutsetw(4)year-setw(2)month-setw(2)dayendl;
cout.fill( );
}
bool
文档评论(0)