C++课本第四章例题
时钟类的完整例题
#include <iostream> using namespace std; class Clock{ private : int hour,minute,second; public: void setTime(int hour=0,int minute=0,int second=0); void showTime(); }; void Clock::setTime(int newH,int newM,int newS) { hour=newH; minute=newM; second=newS; } void Clock::showTime() { cout<<hour<<"/"<<minute<<"/"<<second<<endl; } int main() { Clock myclock; myclock.setTime(); myclock.showTime(); myclock.setTime(11,2,3); myclock.showTime(); }
点和线的组合类例题
1 #include <iostream> 2 #include <cmath> 3 using namespace std; 4 class Point{ 5 public: 6 Point(int xx=0,int yy=0){ 7 x=xx; 8 y=yy; 9 } 10 Point(Point &p); 11 int getx(){ 12 return x; 13 } 14 int gety(){ 15 return y; 16 } 17 private: 18 int x; 19 int y; 20 }; 21 Point::Point(Point &p) 22 { 23 x=p.x; 24 y=p.y; 25 cout<<"copy"<<endl; 26 } 27 class Line{ 28 public: 29 Line(Point xp1,Point xp2); 30 Line(Line &l); 31 double getline(){ 32 return len; 33 } 34 private: 35 double len; 36 Point p1,p2; 37 }; 38 Line::Line(Point xp1,Point xp2):p1(xp1),p2(xp2){ 39 cout<<"line"<<endl; 40 double x=static_cast<double> (p1.getx()-p2.getx()); 41 double y=static_cast<double> (p1.gety()-p2.gety()); 42 len=sqrt(x*x+y*y); 43 } 44 Line::Line(Line &l):p1(l.p1),p2(l.p2){ 45 cout<<"copy line"<<endl; 46 len=l.len; 47 } 48 int main() 49 { 50 Point myp1(1,1),myp2(4,5); 51 Line line(myp1,myp2); 52 Line line2(line); 53 cout<<"the length of the line is:"; 54 cout<<line.getline()<<endl; 55 cout<<"the length of the line2 is:"; 56 cout<<line2.getline()<<endl; 57 return 0; 58 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?