5月6日打卡

例4-4

题目描述:

类的组合,线段类。

我们使用一个类来描述线段,使用4.3节中Point类的对象来表示端点。这个问题可以用类的组合来解决 ,使Line类包括Point类的两个对象p1和p2,作为其数据成员。Line类具有计算线段长度的功能,在构造函数中实现。

代码部分:

#include<iostream>
#include<cmath>
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;
        cout << "Calling the copy constructor of Point" << endl;
    }
    int getX()
    {
        return x;
    }
    int getY()
    {
        return y;
    }
};
class Line {
private:
    Point p1, p2;
    double len;
public:
    Line(Point xp1, Point xp2):p1(xp1),p2(xp2)
    {
        cout << "Calling constructor of Line" << endl;
        double x = p1.getX() - p2.getX();
        double y = p1.getX() - p2.getX();
        len = sqrt(x * x + y * y);
    }
    Line(Line& l)
    {
        len = l.len;
        cout << "Calling the copy constructor of Line" << endl;
    }
    double getLen() { return len;}

};
int main()
{
    Point myp1(1, 1), myp2(4, 5);
    Line line(myp1, myp2);
    Line line2(line);
    cout << "The length of the line is:";
    cout << line.getLen() << endl;
    cout << "The length of the line2 is :";
    cout << line2.getLen()<< endl;
    return 0;
}

例4-7

题目描述:

用结构体表述学生基本信息

代码部分:

#include<iostream>
using namespace std;
struct Student {
    int num;
    string name;
    char sex;
    int age;
};
int main()
{
    Student stu = { 97001,"Lin Lin",'F',19 };
    cout << "Num:" << stu.num << endl;
    cout << "Name:" << stu.name << endl;
    cout << "Sex:" << stu.sex << endl;
    cout << "Age:" << stu.age << endl;
    return 0;
}

例4-8

题目描述:

使用联合体保存成绩信息,并且输出。

 

posted @ 2023-05-07 11:24  石铁生  阅读(14)  评论(0编辑  收藏  举报