您的位置:首页 > 其它

第十一周 项目四:(1)类族的设计

2015-05-18 20:54 281 查看
问题及代码:

/*
* Copyright (c) 2015, 烟台大学计算机学院
* All rights reserved.
* 文件名称:Project4.cpp
* 作    者:李楠
* 完成日期:2015年5月18日
* 版 本 号:v1.0
*
* 问题描述:(1)先建立一个Point(点)类,包含数据成员x,y(坐标点),实现需要的成员函数,并设计main函数完成测试;
* 输入描述:略
* 程序输出:略
*/
#include <iostream>
using namespace std;
class Point
{
public:
Point(double x=0,double y=0);
double getX( );
double getY( );
friend ostream & operator<<(ostream &,const Point &);
void setPoint(double,double);
protected:
double x,y;
};
double Point::getX( )
{
return x;
}
double Point::getY( )
{
return y;
}
Point::Point(double a,double b)
{
x=a;
y=b;
}
ostream & operator<<(ostream &output,const Point &p)
{
output<<"("<<p.x<<","<<p.y<<")"<<endl;
return output;
}
void Point::setPoint(double a,double b)
{
x=a;
y=b;
}
int main( )
{
Point p(10.2,4.5);
cout<<"x="<<p.getX( )<<endl;
cout<<"y="<<p.getY( )<<endl;
p.setPoint(5,7);
cout<<"p:"<<p<<endl;
return 0;
}

知识点总结:
本来想重载">>"的但是发现x,y是私有,所以只能通过函数来调用!!!
之所以将成员函数写成protected是因为后续还要写他的子类,所以应该提前就这样写,免去修改的麻烦!!
其实也可以不重载"<<",直接用函数输出!!

/*
* Copyright (c) 2015, 烟台大学计算机学院
* All rights reserved.
* 文件名称:Project4.cpp
* 作    者:李楠
* 完成日期:2015年5月18日
* 版 本 号:v1.0
*
* 问题描述:(1)先建立一个Point(点)类,包含数据成员x,y(坐标点),实现需要的成员函数,并设计main函数完成测试;
* 输入描述:略
* 程序输出:略
*/
#include <iostream>
using namespace std;
class Point
{
public:
Point(double x=0,double y=0);
double getX( );
double getY( );
void putpoint();
void setPoint(double,double);
protected:
double x,y;
};
double Point::getX( )
{
return x;
}
double Point::getY( )
{
return y;
}
Point::Point(double a,double b)
{
x=a;
y=b;
}
void Point::putpoint()
{
cout<<"("<<x<<","<<y<<")"<<endl;
}
void Point::setPoint(double a,double b)
{
x=a;
y=b;
}
int main( )
{
Point p(10.2,4.5);
cout<<"x="<<p.getX( )<<endl;
cout<<"y="<<p.getY( )<<endl;
p.setPoint(5,7);
cout<<"p:";
p.putpoint();
return 0;
}


运行结果:

待传

学习心得:

先一步一步完成,跟着提示走,并没有很麻烦!


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: