【发布时间】:2016-04-17 11:50:30
【问题描述】:
我编写了一个不可变类 Coords,只有两个成员 - const int x 和 const int y。但是,编译器希望我编写一个赋值运算符,据我所知,它对于不可变类型没有意义。这是一个例子:
//location is a Coords* and Coords::DOWN is a static const Coords&.
Coords& next = Coords(location);
next = next + Coords::DOWN;
Intellisense 不喜欢在第 3 行中使用“=”。我认为问题在于我已经为“下一个”分配了内存,所以当我想用其他东西替换那个内存中的东西时,它不喜欢那样。我对么?我该如何解决这个问题?
谢谢!
【问题讨论】:
-
如果你的类型是“不可变的”,你希望这个 mutating 操作如何工作?
-
Coords(location)创建一个临时对象(您有一个悬空引用),并且您不会重新分配给引用,而是分配给引用的Coords对象。 -
"Intellisense 不喜欢在第 3 行使用 '='。" 它也不应该喜欢第 2 行,但这是他们长期存在的 VC++ 编译器错误不太可能修复。
-
抱歉,我不小心按了最后一条评论的输入,现在它不允许我编辑。我的意思是:我不想要静音操作,我希望将 next 设置为 next + Coords::DOWN 的结果。已替换,未修改。我有点明白这就是指针的用途?但是如果我将next设为指针,那么“next = next + Coords::DOWN会导致内存泄漏,对吧?我不太擅长这个。抱歉打扰了大家。我做了一些编辑以改进code: //location 是一个 Coords* 并且 Coords::DOWN 是一个静态的 const Coords&.Coords next(location); next = next + Coords::DOWN;
标签: c++ operator-overloading immutability operator-keyword assignment-operator