const指针成员和operator =

时间:2013-02-07 09:14:42

标签: c++

class Point {
public:
    Point(int x, int y) : { x = new int(x); y = new int(y) }
    ...
    ...
    Point& operator=(const Point& other) {
        if(this!=&other){
            delete x;
            delete y;
            x = new int(*other.x);
            y = new int(*other.y);
        }
        return *this;
    }
private:
    const int* x;
    const int* y;
}

即使这个x和y已经初始化,这个operator =的实现也会工作吗?删除一个const指针允许我们重新分配吗?

1 个答案:

答案 0 :(得分:6)

这不是const指针,而是指向const的指针。所以你可以修改指针,你不能指向它。

const指针是

int* const x;

然后你的代码就不会编译了。