C ++ constant specifier

I have a Point2D class as follows:

class Point2D{
        int x;
        int y;
    public:
        Point2D(int inX, int inY){
            x = inX;
            y = inY;
        };

        int getX(){return x;};
        int getY(){return y;};
    };

Now I have defined the class Lineas:

class Line {
Point2D p1,p2;
public:
 LineVector(const Point2D &p1,const Point2D &p2):p1(p1),p2(p2) {
        int x1,y1,x2,y2;
        x1=p1.getX();y1=p1.getY();x2=p2.getX();y2=p2.getY();
 }
};

Now the compiler gives an error in the last line (where it is called getX(), etc.):

error: passing const Point2Das an thisargument int Point2D::getX()discards qualifiers

If I delete the keyword constin both places, it will compile successfully.

What mistake? This is because getX()etc. Defined in line? Is there any way to fix this while keeping them inline?

+3
source share
6 answers

getX() getY() const. ++ const const. , int getX() const{..}. const, , - - . const, , const.

+8

, const, , . getX getY const, :

    int getX() const {return x;}
    int getY() const {return y;}

, .

+2

, getX() .. const. :

    int getX() const {return x;};
    int getY() const {return y;};
  //  ---------^^^^^

p1 p2 const, const. const getX() , this (.. p1 p2), .

+2

getX

int getX() const {...}
+1

getX(), getY() const:

int getX() const {return x;}
int getY() const {return y;}

const ,

+1

- "const", .

class Point2D{
    int x;
    int y;
public:
    Point2D(int inX, int inY){
        x = inX;
        y = inY;
    };

    int getX() const {return x;};
    int getY() const {return y;};
    //         ^^^^^
};

This is about a hidden parameter this. It thiswill either be of type const Point2D*or Point2D*. If you have a reference to the constant Point2D, you cannot call non-const functions, because there is no implicit conversion from const Point2D*to Point2D*.

+1
source

Source: https://habr.com/ru/post/1742241/


All Articles