In the code below, why function SymmetricAxis can change x and y in p3? I think that const function will not allowed to change member's value. But it does, so I am confused. Besides, if I change p3 to const CPoint p3, the compiler do not allow me to do this. But if p3 is not const, the program can change the member in p3.
#include<iostream>
#include<math.h>
using namespace std;
class CPoint
{
private:
double x;
double y;
public:
CPoint(double xx = 0, double yy = 0) : x(xx), y(yy) {};
double Distance(CPoint p) const;
double Distance0() const;
CPoint SymmetricAxis(char style) const;
void input();
void output();
};
void CPoint::input(){
cout << "Please enter point location: x y" << endl;
cin >> x >> y;
}
void CPoint::output(){
cout << "X of point is: " << x << endl << "Y of point is: " << y << endl;
}
CPoint CPoint::SymmetricAxis(char style) const{
CPoint p1;
switch (style){
case 'x':
p1.y = -y;
break;
case 'y':
p1.x = -x;
case '0':
p1.x = -x;
p1.y = -y;
break;
}
return p1;
}
int main(){
CPoint p1, p2(1, 10), p3(1,10);
p1.input();
p1.output();
p3 = p1.SymmetricAxis('0');
p3.output();
return 0;
}
SymmetricAxisdoes not change the value ofp3.SymmetricAxismerely returns a newCPointas an unnamed temporary value. (That temporary value is initialized by the local variablep1in the body ofSymmetricAxis.)The copy-assignment operator copies this temporary value over the value of p3.
The
constqualifier onSymmetricAxisonly means that the callp1.SymmetricAxis('0')will not changep1. It says nothing about what you assign the result of that call to.(Implementation / optimization note: The compiler is allowed to optimize away one or more of these copies, but the meaning of
constin this context presumes these copies happen.)