C++实验: 类与对象(一)

C++实验: 类与对象(一)

1. 实验目的

(1)掌握声明类的方法,类和类的成员的概念以及定义对象的方法;

(2)初步掌握用类和对象编制基于对象的程序;

(3)学习检查和调试基于对象的程序。

2.实验内容

(1) 改写已知程序,将数据成员改为私有的,将输入和输出的功能改为由成员函数实现,在类体内定义成员函数,然后运行程序;

(2) 在已知的程序中,在类中增加一个对数据成员赋初值的成员函数set_value,然后调试运行;

(3) 编写一个基于对象的程序,用成员函数实现多个功能,求3个长方柱的体积,调试并运行。

3.源代码

(1)

#include <iostream>

using namespace std;

class Time 

  {
          
   public:

       void
set_time(void)

       {
          
   

            cin>>hour;

            cin>>minute;

            cin>>sec;

       }

       void
show_time(void)

       {
          
   

            cout<<hour<<":"<<sec<<endl;

       }

     private:

         int hour;

         int minute;

         int sec;

  };

Time t;

int main()

  {
          
   

   
t.set_time();

    t.show_time();

    return 0;

  } 

 

(2)

class Student

{
          
   

public:

    void display();

    void set_value();

private:

    int num;

    char name[20];

    char sex;

};

 

#include <iostream>

#include "student.h"

using namespace std;

int main()

{
          
   

    Student
stud;

    stud.set_value();

    stud.display();

    return 0;

}

void
Student::display()

{
          
   

cout<<"num:"<<num<<endl;

    cout<<"name:"<<name<<endl;

    cout<<"sex:"<<sex<<endl;

}

void
Student::set_value()

{
          
   

    cin>>num;

    cin>>name;

    cin>>sex;

}

 

(3)

#include <iostream>

using namespace std;

class Box

{
          
   

public:

    void get_value();

    float volume();

    void display();

public:

    float length;

    float width;

    float height;

};

void Box::get_value()

{
          
   

    cout<<"Please input length,width and height:";

    cin>>length;

    cin>>width;

    cin>>height;

}

float Box::volume()

{
          
   

    return(length*width*height);

}

voidBox::display()

{
          
   

    cout<<volume()<<endl;

}

int main()

{
          
   

    Box box1,box2,box3;

    box1.get_value();

    cout<<"volume of box1 is";

    box1.display();

    box2.get_value();

    cout<<"volume of box2 is";

    box2.display();

    box3.get_value();

    cout<<"volume of box3 is";

    box3.display();

    return 0;

}

4.运行结果

经验分享 程序员 微信小程序 职场和发展