第四章部分例题(1)

例4-1

题目描述:时钟类的完整程序

代码实现:

#include<iostream>
using namespace std;
class Clock
{
private:
    int hour, minute, second;
public:
    void setTime(int newH = 0, int newM = 0, int newS = 0)
    {
        hour = newH;
        minute = newM;
        second = newS;
    }
    void showTime()
    {
        cout << hour << ":" << minute << ":" << second << endl;
    }
};
int mian()
{
    Clock myClock;
    cout << "First time set and output:" << endl;
    myClock.setTime();
    myClock.showTime();
    cout << "Second time set and output:" << endl;
    myClock.setTime(8, 30, 30);
    myClock.showTime();
    return 0;
}

例4-2

题目描述:Point类的完整程序。

代码实现:

#include<iostream>
using namespace std;
class Point {
private:
    int x,y;
public:
    Point(int xx = 0, int yy = 0)
    {
        x = xx;
        y = yy;
    }
    Point(Point& p)
    {
        x = p.x;
        y = p.y;

    }
    int getX()
    {
        return x;
    }
    int getY()
    {
        return y;
    }
};
void fun1(Point p)
{
    cout<< p.getX() << endl;

}
Point fun2()
{
    Point a(1, 2);
    return a;
}
int main()
{
    Point a(4, 5);
    Point b = a;
    cout << b.getX() << endl;
    fun1(b);
    b = fun2();
    cout << b.getX ()<< endl;
    return 0;
}

 

posted on 2023-04-26 20:45  石铁生  阅读(25)  评论(0)    收藏  举报