C++项目 体验常成员函数

【项目1-体验常成员函数】

  设计平面坐标点类,计算两点之间距离、到原点距离、关于坐标轴和原点的对称点等。在设计中,由于求距离、求对称点等操作对原对象不能造成任何改变,所以,将这些函数设计为常成员函数是合适的,能够避免数据成员被无意更改。

#include<iostream>
#include<math.h>
using namespace std;
class Cpoint{
public: 
	Cpoint(float x,float y):xpoint(x),ypoint(y){};
	float distance(char style) const;
	float pointdistance(Cpoint p) const;
	void symmetricaxis(char style) const; 
private:
	float xpoint;
	float ypoint;
};
float Cpoint::distance(char style) const
{ 
	switch (style)
	{
	case 'o':
		return sqrt(xpoint*xpoint+ypoint*ypoint);break;
	case 'x':
		return ypoint;break;
	case 'y':
		return xpoint;break;
	default:
		return 0;
	}
} 

float Cpoint::pointdistance(Cpoint p) const
{
	return sqrt(pow((p.xpoint-xpoint),2)+pow((p.ypoint-ypoint),2));
}

void Cpoint::symmetricaxis(char style) const
{
	switch(style)
	{
	case 'o':
		cout<<"the symmetricaxis is origin: ("<<-xpoint<<","<<-ypoint<<")"<<endl;break;
	case 'x':
		cout<<"the symmetricaxis is xaxis: ("<<xpoint<<","<<-ypoint<<")"<<endl;break;
	case 'y':
		cout<<"the symmetricaxis is yaxis: ("<<-xpoint<<","<<ypoint<<")"<<endl;break;
	}
}
void main()
{
	Cpoint cpoint(2,3),p(2,1);
	cout<<cpoint.distance('o')<<endl;
	cout<<cpoint.distance('x')<<endl;
	cout<<cpoint.distance('y')<<endl;
	cpoint.symmetricaxis('o');
	cpoint.symmetricaxis('x');
	cpoint.symmetricaxis('y');
	cout<<cpoint.pointdistance(p)<<endl;
}



你可能感兴趣的:(类,常成员函数)