【问题标题】:Const function in class can change the member value?类中的const函数可以改变成员值吗?
【发布时间】: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++


    【解决方案1】:

    SymmetricAxis 不会改变p3 的值。 SymmetricAxis 仅返回一个新的 CPoint 作为未命名的临时值。 (该临时值由 SymmetricAxis 主体中的局部变量 p1 初始化。)

    复制赋值运算符将这个临时值复制到 p3 的值上。

    SymmetricAxis 上的 const 限定符仅表示调用 p1.SymmetricAxis('0') 不会更改 p1。它没有说明您将该调用的结果分配给什么。

    (实现/优化说明:允许编译器优化掉这些副本中的一个或多个,但const 在此上下文中的含义假定这些副本发生。)

    【讨论】:

      【解决方案2】:

      您正在更改函数内部的局部变量,而不是任何成员变量。例如,如果你写this-&gt;y = 0,你会得到一个编译错误。 const 限定符仅承诺不会更改 *this

      为了澄清,*this 指的是p1(您调用该函数。)您创建一个也称为p1 的局部变量,您可以对其进行修改(因为它与this 不同)。 p3 根本不起作用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-09-29
        • 2011-06-04
        • 1970-01-01
        • 1970-01-01
        • 2017-10-11
        • 2011-11-15
        • 1970-01-01
        • 2012-07-19
        相关资源
        最近更新 更多