第05章c程序结构6课时.pptxVIP

  • 0
  • 0
  • 约8.2千字
  • 约 95页
  • 2021-11-28 发布于北京
  • 举报
第五章 C++程序的结构;本章主要内容;5.1 作用域与可见性;5.1.1 作用域;函数原型的作用域;局部作用域;类作用域;文件作用域;可见性;例 5.1;对象的生存期;静态生存期;例;例;动态生存期;例5-2 变量的生存期与可见性; int main() { static int a; // 静态局部变量,有全局寿命,局部可见。 int b = -10; // b, c为局部变量,具有动态生存期。 int c = 0; cout ---MAIN---\n; cout i: i a: a b: b c: cendl; c += 8; other(); cout---MAIN---\n; cout i: i a: a b: b c: cendl; i += 10; other(); return 0; };例5-3具有静态、动态生存期对象的时钟程序;Clock::Clock() : hour(0), minute(0), second(0) { } //构造函数 void Clock::setTime(int newH, int newM, int newS) { //三个形参均具有局部作用域 hour = newH; minute = newM; second = newS; } void Clock::showTime() { cout hour : minute : second endl; };Clock globClock;//声明对象globClock, //具有静态生存期,文件作用域 int main() { //主函数 cout First time output: endl; //引用具有文件作用域的对象: globClock.showTime();//对象的成员函数具有类作用域 globClock.setTime(8,30,30); Clock myClock(globClock); //声明具有块作用域的对象myClock coutSecond time output:endl; myClock.showTime(); //引用具有块作用域的对象 return 0; };程序的运行结果为: First time output: 0:0:0 Second time output: 8:30:30 ;数据与函数;使用局部对象;使用全局对象;使用类的成员变量进行传递;静态成员;#include iostream.h class static_myclass // 有静态数据成员的 class { public: static int a; }; int static_myclass::a = 5; void main() { static_myclass obj1, obj2; obj1.a = 10; //引用方法一 static_myclass::a = 20; //引用方法二 cout obj1.a endl; cout obj2.a endl; cout static_myclass.a endl; };例5-4 具有静态数据成员的 Point类;Point::Point(Point p) { x = p.x; x = p.y; count++; } int Point::count=0; int main() { Point a(4,5); coutPoint A:a.getX(),a.getY(); a.showCount(); Point b(a); coutPoint B:b.getX(),b.getY(); b.showCount(); return 0; };静态函数;静态成员函数举例;静态成员函数举例;具有静态数据、函数成员的 Point类;Point::Point(Point p) { x = p.x; y = p.y; count++; } int Point::count=0; int main() { //主函数实现 Point a(4,5); //声明对象A coutPoint A,a.getX(),a.getY(); Point::showCount(); //输出对象个数 Point b(a); //声明对象B coutPoint B,b.GetX(),b.GetY(); Point:: showCount(); //输出对象个数 return 0; };友元;友元函数;例5-6 使用友元函数计算两

文档评论(0)

1亿VIP精品文档

相关文档