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 }
复制代码

 

posted @   新晋软工小白  阅读(90)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示