C++第四章课后习题
定义一个Circle类,有半径数据成员,有求面积函数,构造一个Circle对象测试。
1 #include <iostream> 2 using namespace std; 3 #define PI 3.1415926 4 class Circle{ 5 private: 6 double radius; 7 public: 8 void getArea() 9 { 10 cout<<PI*radius*radius; 11 } 12 Circle(double r):radius(r){ 13 } 14 }; 15 int main() 16 { 17 double x; 18 cin>>x; 19 Circle c(x); 20 c.getArea(); 21 }
定义一个树类,有成员函数树龄,成员函数增长几年,显示年龄函数。
#include <iostream> using namespace std; class Tree{ private: int ages; public: Tree(int a=0):ages(a){ } void grow(int years) { ages=ages+years; } void age() { cout<<ages<<endl; } }; int main() { int x; cin>>x; Tree t(x); t.age(); t.grow(5); t.age(); }
定义一个负数类,实现负数的加法。
1 #include <iostream> 2 using namespace std; 3 class Complex{ 4 private: 5 double x,y; 6 public: 7 Complex(double a,double b):x(a),y(b){ 8 } 9 Complex(double a):x(a),y(0){ 10 } 11 double getx() 12 { 13 return x; 14 } 15 double gety() 16 { 17 return y; 18 } 19 void add(Complex c) 20 { 21 x=x+c.getx(); 22 y=y+c.gety(); 23 } 24 void show() 25 { 26 cout<<x<<"+"<<y<<"i"<<endl; 27 } 28 }; 29 int main() 30 { 31 Complex c1(3,5); 32 Complex c2=4.5; 33 c1.add(c2); 34 c1.show(); 35 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?