[英]const pointer members and operator=
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指針是否可以重新分配它?
這不是一個const
指針,而是一個指向const
。 因此,您可以修改指針,但不能修改它指向的指針。
const
指針是
int* const x;
然后您的代碼將無法編譯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.