我有一个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;};
};
现在我已将类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();
}
};
现在编译器在最后一行(调用getX()
等)中给出了错误:
错误:将
const Point2D
作为this
参数传递int Point2D::getX()
丢弃限定符
如果我在两个地方删除const
关键字,那么它会成功编译。
错误是什么?是因为getX()
等是内联定义的吗?有没有办法纠正这种保留内联?
答案 0 :(得分:8)
您尚未将getX()
和getY()
方法声明为const。在C ++中,您只能从const对象调用const方法。所以你的函数签名应该是int getX() const{..}
。通过将它们定义为const方法,您告诉编译器您不会修改此方法中的任何成员变量。由于你的对象是一个const对象,所以它不应该被修改,因此你只能在它上面调用const方法。
答案 1 :(得分:2)
为了保证参数的常量,只能对它们调用const方法,否则编译器无法确定方法不会更改值。将getX和getY声明为const,如下所示:
int getX() const {return x;}
int getY() const {return y;}
请注意,不需要在结束大括号后使用分号。
答案 2 :(得分:2)
这是因为getX()
等不是常量。您可以像这样定义它们:
int getX() const {return x;};
int getY() const {return y;};
// ---------^^^^^
由于p1
和p2
是const引用,因此必须只调用const方法。但如果const
中没有getX()
修饰符,则会假定他们修改this
(即p1
和p2
),这是不允许的。
答案 3 :(得分:1)
尝试将您的getX函数定义为
int getX() const {...}
答案 4 :(得分:1)
您必须将getX()
,getY()
函数声明为const:
int getX() const {return x;}
int getY() const {return y;}
const关键字告诉编译器方法不会改变对象的状态
答案 5 :(得分: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
参数。 this
的类型为const Point2D*
或Point2D*
。如果您对const Point2D有引用,则无法调用非const成员函数,因为没有从const Point2D*
到Point2D*
的隐式转换。