定义常成员函数: 返回值类型 成员函数名[(形参表列)] const;
不论对于常成员变量或是非常变量,还是常对象的数据成员变量,常成员函数都只能是引用这些变量,而不可以改变。
若在程序中需要用改变值的成员变量,可以重新定义一个中间变量,通过改变中间变量的值来实现功能。
/*
设计平面坐标点类,计算两点之间距离、到原点距离、关于坐标轴和原点的对称点等。
在设计中,由于求距离、求对称点等操作对原对象不能造成任何改变,所以,
将这些函数设计为常成员函数是合适的,能够避免数据成员被无意更改。*/
//定义点的类,头文件class.h
class Point
{private:
int x,y;
public:
Point (int a,int b):x(a),y(b){};//带参数的构造函数
Point( ){};//默认构造
void SetP(int a,int b);
void Getp( );
void Distance_p(Point p);//两点之间的距离,对象包含对象
void Distance_Yuan( );
//将成员函数声明为常量,在定义此函数时也需要加“const”,成员函数被定义为常量时了,只能引用成员变量而不能修改
void Symmetry_x( ) const;void Symmetry_y( )const;
void Symmetry_o( )const;
};
//源文件
#include<iostream>
#include<cmath>
using namespace std;
#include "class.h"
int main()
{
Point p1,p2;
p1.SetP(30,40);
p2.SetP(40,50);
p1.Distance_Yuan();
//两点距离
p1.Distance_p(p2);
p2.Distance_p(p1);
cout<<"关于原点对称: "<<endl;
p1.Symmetry_o( );
cout<<"关于Y对称: "<<endl;
p1.Symmetry_y();
cout<<"原始点: "<<endl;
p1.Getp();
return 0;}
void Point::SetP(int a,int b )
{
x=a;
y=b;
}
void Point::Getp( )
{
cout<<"x= "<<x<<'\t'
<<"y= "<<y
<<endl;
}
void Point::Distance_p(Point p)
{
int d1=0;
d1=sqrt((x-p.x)*(x-p.x)+(y-p.y)*(y-p.y));
cout<<"the distance of the two point is: "<<d1<<endl;
}
void Point::Distance_Yuan( )
{ int d=0;
d=sqrt(x*x+y*y);
cout<<"the distance of the point and the 0 is: "<<d<<endl;
}
void Point::Symmetry_x( )const
{
Point p1;//调用默认构造函数---中间变量
p1.x=-x;p1.y=y;
cout<<"x= "<<p1.x<<'\t'
<<"y= "<<p1.y<<endl;
//此处可以将函数返回值设为Point型,return p1;
}
void Point::Symmetry_y( )const
{
Point p2(this->x,this->y);//复制带参数的构造函数
p2.x=x;p2.y=-y;
cout<<"x= "<<p2.x<<'\t'
<<"y= "<<p2.y<<endl;
}
void Point::Symmetry_o( )const
{
Point p3;
p3.x=-x;p3.y=-y;
cout<<"x= "<<p3.x<<'\t'
<<"y= "<<p3.y<<endl;
}
改进:
将三个对称成员函数合成一个,通过判断参数值来确定是哪种类型的对称且有返回值: Point SymmetricAxis(char style) const