我又回来了,这次发布的是mooc的编程题
使用对象成员构成新类。(10分)
题目内容:
注意:程序需要加上#include头文件
要求先定义一个Point类,用来产生平面上的点对象。两点决定一条线段,即线段由点所构成。因此,Line类使用Point类的对象作为数据成员,然后在Line类的构造函数里求出线段的长度。
class Point
{
private:
double X, Y;
public:
Point( double a, double b );
Point( Point &p );
double GetX( ) ;
double GetY( ) ;
};
class Line
{
private:
Point A , B ; //定义两个Point类的对象成员
double length ;
public:
Line( Point p1 , Point p2 ) ;//Line类的构造函数原型,函数体类外实现
double GetLength( )
};
在main( )中定义线段的两个端点,并输出线段的长度。
输入格式:
cin>>a>>b>>c>>d;
提示:a,b,c,d用于存储两个端点的坐标。
输出格式:
cout<<setprecision(3)<<L.GetLength()<<endl;
输入样例:
0 0 2 2
输出样例:
2.83
参考程序:
#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;
class Point
{
private:
double X, Y;
public:
Point( double a, double b );
Point( Point &p );
double GetX( ) ;
double GetY( ) ;
};
class Line
{
private:
Point A , B ; //定义两个Point类的对象成员
double length ;
public:
Line( Point p1 , Point p2 ) ;//Line类的构造函数原型,函数体类外实现
double GetLength();
};
Point::Point(double a,double b)
{X=a;
Y=b;
}
Point::Point(Point &p)
{X=p.X;
Y=p.Y;}
double Point::GetX()
{return X;
}
double Point::GetY()
{return Y;
}
Line::Line(Point p1,Point p2):A(p1),B(p2)
{length=sqrt((p1.GetX()-p2.GetX())*(p1.GetX()-p2.GetX())+(p1.GetY()-p2.GetY())*(p1.GetY()-p2.GetY()));
}
double Line::GetLength()
{return length;
}
int main()
{int a,b,c,d;
cin>>a>>b>>c>>d;
Point A(a,b),B(c,d);
Line L(A,B);
cout<<setprecision(3)<<L.GetLength()<<endl;
}
第二题:
定义一个学生类,有如下基本成员:
(1)私有数据成员:年龄 int age;
姓名 string name;
(2)公有静态数据成员:学生人数 static int count;
公有成员函数:
构造函数: 带参数的构造函数Student( int m , string n );
不带参数的构造函数Student( );
析构函数: ~Student( );
输出函数: void Print( )const;
主函数的定义及程序的运行结果如下,请完成类的定义及类中各函数的实现代码,补充成一个完整的程序。
int main( )
{
cout << "count=" << Student::count << endl;
Student s1,*p = new Student( 23, "ZhangHong" ) ;
s1.Print( ) ;
p -> Print( ) ;
delete p;
s1.Print( ) ;
Student Stu[4];
cout << "count=" << Student::count << endl ;
return 0;
}
输入格式:
输出格式:
输入样例:
输出样例:
count=0
2
Name=NoName , age=0
2
Name=ZhangHong , age=23
1
Name=NoName , age=0
count=5
参考答案:
#include<iostream>
#include<string>
using namespace std;
class Student
{private:
int age;
string Name;
public:
Student(int m,string n);
Student();
~Student();
static int count;
void Print()const;
};
int Student::count=0;
Student::Student(int m,string n)
{age=m;
Name=n;
count++;
}
Student::Student()
{age=0;
Name="NoName";
count++;
}
Student::~Student()
{count--;
}
void Student::Print()const
{cout<<count<<endl;
cout<<"Name="<<Name<<" , age="<<age<<endl;//这里的“ , age=”逗号前后都用空格不然会显示输出格式不对
}
int main( )
{
cout << "count=" << Student::count << endl;
Student s1,*p = new Student( 23, "ZhangHong" ) ;
s1.Print( ) ;
p -> Print( ) ;
delete p;
s1.Print( ) ;
Student Stu[4];
cout << "count=" << Student::count << endl ;
return 0;
}
希望能帮助到大家
惯例求赞
本文解析了如何使用对象成员创建Point和Line类,以及定义一个包含年龄和姓名的学生类。通过实例化和操作,展示了如何在main函数中计算线段长度并输出学生信息。
1620





