简体   繁体   中英

Const function in class can change the member value?

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;
}

SymmetricAxis does not change the value of p3 . SymmetricAxis merely returns a new CPoint as an unnamed temporary value. (That temporary value is initialized by the local variable p1 in the body of SymmetricAxis .)

The copy-assignment operator copies this temporary value over the value of p3.

The const qualifier on SymmetricAxis only means that the call p1.SymmetricAxis('0') will not change p1 . 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 const in this context presumes these copies happen.)

You're changing variables on a local inside the function, not any of the member variables. If you for example write this->y = 0 , you will get a compile error. The const qualifier only promises not to change *this .

To clarify, *this refers to p1 (which you call the function on.) You create a local variable also called p1 which you are allowed to modify (because it's not the same this ). p3 does not come into play at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM