第一题
要求先定义一个Point类,用来产生平面上的点对象。两点决定一条线段,即线段由点所构成。因此,Line类使用Point类的对象作为数据成员,然后在Line类的构造函数里求出线段的长度。
代码
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
class Point
{
private:
double X, Y;
public:
Point( double a, double b ):X(a),Y(b)
{
}
double GetX( )
{
return X;
}
double GetY( )
{
return Y;
}
};
class Line
{
private:
Point A , B ; //定义两个Point类的对象成员
double length ;
public:
Line( Point p1 , Point p2 ):A(p1),B(p2)
{
}
double GetLength()
{
length=sqrt((A.GetX()-B.GetX())*(A.GetX()-B.GetX())+(A.GetY()-B.GetY())*(A.GetY()-B.GetY()));
return length;
}
};
main()
{
double 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;
代码
#include<iostream>
using namespace std;
class Student
{
private:
int age=0;
string name="NoName";
public:
static int count;
Student(int m,string n):age(m),name(n)
{
count++;
}
Student()
{
count++;
}
~Student()
{
count--;
}
void Print( )const
{
cout<<count<<endl;
cout<<"Name="<<name<<" , "<<"age="<<age<<endl;
}
};
int Student::count=0;
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;
}