0
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 指针是否允许我们重新分配它?

4

1 回答 1

7

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

一个const指针是

int* const x;

然后您的代码将无法编译。

于 2013-02-07T09:15:48.370 回答