【C++学习笔记7】实验7-类与对象知识进阶(1)

【描述】
请根据main函数中对该类的操作,补充类实现部分完成代码。
该类有个私有静态变量count记录该类的所有对象数,主函数将会在不同语句之后输出对象数,只有正确地实现该类,保证count正确记录该类的对象数,才能输出正确的结果。
【输入】
没有输入。
【输出】
主函数的输出已经写好。

#include <iostream>
#include <string>
using namespace std;
class Student {
    
    
private:
    int id;
    static int count; 
public:



/* 请在此处编写相关代码 */

static void InitCount(){
    
    
    count=0;
}

Student(){
    
    
    count++;
}
Student(int a){
    
    //如果输入一个整数
    id=a;
    count++;
}
Student(const Student &stu){
    
    //复制构造函数,构造一个对象,count+1
    id=stu.id;
    count++;
}
~Student(){
    
    //析构完一个,count-1
    count--;
}

friend void PrintCount();//用友元,可以直接访问对象的私有数据成员count
friend void Print(Student s);//可以直接访问私有成员s2.id,无需get,数据共享

/* 请在此处编写相关代码 */




};
int Student::count;
void PrintCount() {
    
    
    cout << "Total " << Student::count << " students" << endl;
}
void Print(Student s) {
    
    
    cout << "the id is " << s.id << endl;
}
int main() {
    
    
    Student::InitCount();
    Student s;
    PrintCount();
    Student s1(10);
    Student s2(s1);
    PrintCount();
    Print(s2);	// 调用拷贝构造函数,调用结束调用析构函数 
    PrintCount();
    return 0;
}

【描述】
声明并实现一个Line类,表示线段。Line类包括:
Point类的私有对象数据成员start和end,表示线段的两个端点。
有参构造函数,将线段端点设置为给定的参数。
成员函数slope,计算线段的斜率。
【输入】
输入4个数,分别表示点1坐标(x1, y1)和点2坐标(x2, y2)。
【输出】
输出直线的斜率。
【输入示例】
10 20 30 70
【输出示例】
2.5
【提示】
Point类可以参阅《程序基础基础——以C++为例》第5章实验1。
【来源】
《程序设计基础——以C为例》第6章实验1。

#include <iostream>
#include <cmath>
using namespace std;


/* 请在此处分别编写Point类和Line类 */
class Line;//向前声明
class Point{
    
    
    
    private:
        double start;
        double end;
    public:
        friend Line;//Line可以访问Point的私有成员了  
        Point(double &x,double &y){
    
    
            start=x;
            end=y;
        }
};

class Line{
    
    
    private:
        double k;
    public:
        Line(const Point &x,const Point &y){
    
    //复制构造函数
            k=(y.end-x.end)/(y.start-x.start);//已知两点,计算斜率
        }

        double slope(){
    
    //输出
            return k;
        }
};

/* 请在此处分别编写Point类和Line类 */


int main() {
    
    
    double x1, y1, x2, y2;
    cin >> x1 >> y1 >> x2 >> y2;
    Point start(x1, y1);
    Point end(x2, y2);
    Line line(start, end);
    cout << line.slope() << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_49868778/article/details/116299122
今日推荐