【发布时间】:2013-12-15 04:56:37
【问题描述】:
在下面的代码中,为什么函数 SymmetricAxis 可以改变 p3 中的 x 和 y? 我认为 const 函数不允许更改成员的值。但确实如此,所以我很困惑。 此外,如果我将 p3 更改为 const CPoint p3,编译器不允许我这样做。但是如果 p3 不是 const,程序可以改变 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;
}
【问题讨论】:
标签: c++