NJUPT面向对象程序设计及C++mooc编程(第四章)--by sCh3n

第一题

要求先定义一个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;

}

  • 6
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sh4ngchen

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值