大学CC++程序设计案例教程张殿龙)c_cpp10课件教学.pptVIP

  • 8
  • 0
  • 约2.34万字
  • 约 116页
  • 2017-03-06 发布于广东
  • 举报

大学CC++程序设计案例教程张殿龙)c_cpp10课件教学.ppt

大学CC++程序设计案例教程张殿龙)c_cpp10课件教学.ppt

友元类 int main() { Line a[]={Line(1,2,5,4),Line(2,5,2,6),Line(5,4,3,7)}; for (int i=0; i3; i++) a[i].Show(); return 0; } 在线教务辅导网: 更多课程配套课件资源请访问在线教务辅导网 馋死 PPT研究院 POWERPOINT ACADEMY * * this指针 【例10.10】this指针的指向。 // 10-10.cpp #includeiostream using namespace std; class AA { public: AA(int aa=0):a(aa){} void Show() { coutthis = this, a = aendl; } private: int a; }; this指针 int main() { AA a1,a2(9); cout a1 = a1 endl; a1.Show(); cout a2 = a2 endl; a2.Show(); return 0; } this指针 【例10.11】this指针解决形式参数与数据成员同名问题。 // 10-11.cpp #includeiostream using namespace std; class Rect { public: Rect(double length,double width) // 形式参数与数据成员同名 { this-length=length; this-width=width; } void ShowMe() { coutlength\twidth\t2*(length+width)\t length*widthendl; } private: double length,width; }; this指针 int main() { Rect r(10,10); cout长\t宽\t周长\t面积endl; r.ShowMe(); return 0; } this指针 当成员函数需要返回指针或引用时,使用this指针。 【例10.12】this指针的应用。 // 10-12.cpp #includeiostream using namespace std; class Rect { public: Rect(double length,double width) // 形式参数与数据成员同名 { this-length=length; this-width=width; } Rect SetLength(double length) // 引用类型的成员函数 { this-length=length; return *this; } Rect SetWidth(double width) { this-width=width; return *this; } void ShowMe() { coutlength\twidth\t2*(length+width)\tlength*widthendl; } this指针 private: double length,width; }; int main() { Rect r(10,10); cout长\t宽\t周长\t面积endl; r.ShowMe(); r.SetLength(12).SetWidth(15).ShowMe(); return 0; } 对象的动态建立与释放 运算符new的功能是动态分配内存,或者称动态创建对对象。用new建立类的对象时,根据实际情况调用该类的构造函数。 运算符delete用来删除由new建立的对象,释放指针所指向的内存空间。删除对象时,调用析构函数。 对象的动态建立与释放 【例10.13】动态创建对象。 // 10-13.cpp #includeiostream using namespace std; #define PI 3.14159 class Circle { public: Circle(double r = 1):radius(r) // 构造函数 { cout 调用构造函数。radius = radius endl; } double Perim() { return 2*PI*radius; } double Area() { return PI*radius*radius; } ~Circle() // 析构函数 { cout 调用析构函数。radius = radius endl; } private: doub

您可能关注的文档

文档评论(0)

1亿VIP精品文档

相关文档