1. 程式人生 > >C++程式設計第四章答案

C++程式設計第四章答案

4-8

#include <iostream>
using namespace std;
class Dog
{
public:
    Dog(int initialAge=0, int initialWeight=5);
    ~Dog();
    int GetAge()
    {
       return itsAge;
    }
    void SetAge(int age)
    {
        itsAge=age;
    }
    int GetWeight()
    {
       return itsWeight;
    }
    void SetWeight(int weight)
    {
        itsWeight=weight;
    }
private:
    int itsAge, itsWeight;
};
Dog::Dog(int initialAge, int initialWeight)
{
    itsAge=initialAge;
    itsWeight=initialWeight;
}
Dog::~Dog()
{
}
int main()
{
    Dog Dog1(2,5);//Dog是一個類,再定義變數Dog1
    cout<<Dog1.GetAge()<<endl;
    cout<<Dog1.GetWeight()<<endl;
    Dog1.SetAge(7);
    Dog1.SetWeight(10);
    cout<<Dog1.GetAge()<<endl;
    cout<<Dog1.GetWeight()<<endl;
}

4-9

#include <iostream>
#include <cmath>
using namespace std;
class Rectangle{
public:
    int area(int x1,int x2,int y1,int y2);
private:
    int x1,y1,x2,y2;};
int Rectangle::area(int x1,int x2,int y1,int y2)
{
    int S;
    S=(abs(x2-x1))*(abs(y2-y1));
    cout<<S<<endl;
}
int main()
{
    Rectangle Rectangle1;
    int a,b,c,d;
    cin>>a>>b>>c>>d;
    Rectangle1.area(a,b,c,d);
}

4-10
答案如下圖
https://blog.csdn.net/Enterprise_/article/details/79845052

4-11

#include <iostream>
using namespace std;
class Rectangle{
public:
    int S(int aa,int hh);
private:
    int h, a;
};
int Rectangle::S(int aa,int hh)
{
    a=aa;
    h=hh;
    int s;
    s=a*h;
    cout<<s<<endl;
}
int main()
{
    Rectangle Rectangle1;
    int x,y;
    cin>>x>>y;
    Rectangle1.S(x,y);
}

4-13

#include <iostream>
#include <cmath>
using namespace std;
class Circle{
public:
    getArea(int rr);
private:
    int radius;};
Circle::getArea(int rr)
{
    float area;
    radius=rr;
    area=3.1415*radius*radius;
    cout<<area;
}
int main()
{
    Circle Circle1;
    int r;
    cin>>r;
    Circle1.getArea(r);
}

4-14

#include <iostream>
#include <cmath>
using namespace std;
class Tree{
public:
    int setage()//函式過載
    {
        int years;
        years=2;
        return years;
    }
    void setage(int aa);
    int getage();
private:
    int ages;
};
void Tree::setage(int aa)
{
    ages=aa+setage();
}
int Tree::getage()
{
    return ages;
}
int main()
{
    int a;
    cin >>a;
    Tree tree1;
    tree1.setage();
    tree1.setage(a);
    tree1.getage();
    cout<<tree1.getage();
}