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 }

浙公网安备 33010602011771号