c++ - 类中的const函数可以改变成员值吗?

标签 c++

在下面的代码中,为什么函数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;
}

最佳答案

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

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

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

(实现/优化注意事项:允许编译器优化掉这些拷贝中的一个或多个,但在此上下文中 const 的含义假定这些拷贝发生。)

关于c++ - 类中的const函数可以改变成员值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20591348/

相关文章:

c++ - 此 C++ 代码可移植吗?

c++ - GDB如何在运行时评估C++表达式

c++ - 多列列表的 Qt 最佳控件?

c++ - LRU 缓存和多线程

c++ - 比较 (int)double 和 (int)int 时出现异常

c++ - 类内部的Boost Thread无法访问成员变量

c++ - 使用 C++ future 作为函数堆栈中的中间值会导致段错误

C++ 异常抛出 : read access violation

c++ - 如何计算网格中连接的单元格?

c++ - #ifdef DEBUG 与 CMake 独立于平台