C++ const限定符

avd*_*avd 3 c++ inline

我有一个Point2D类如下:

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

        int getX(){return x;};
        int getY(){return y;};
    };
Run Code Online (Sandbox Code Playgroud)

现在我已经将类定义Line为:

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();
 }
};
Run Code Online (Sandbox Code Playgroud)

现在编译器在最后一行(getX()调用etc)中给出了错误:

错误:const Point2D作为discards限定符的this参数传递int Point2D::getX()

如果我const在两个地方删除关键字,那么它会成功编译.

错误是什么?是因为getX()等内联定义?有没有办法纠正这种保留内联?

Nav*_*een 8

你没有声明getX()getY()方法为const.在C++中,您只能从const对象调用const方法.所以你的功能签名应该是int getX() const{..}.通过将它们定义为const方法,您告诉编译器您不会修改此方法中的任何成员变量.由于您的对象是一个const对象,因此不应该对其进行修改,因此您只能在其上调用const const方法.