我有天气课。假设我创建了这个类的一个对象,在此之后,我创建了预增量和后增量,以控制天气的温度。所以,当我做++object;时,温度增加了1,但是当我做object++;时,析构函数被调用,我的指针被删除,我的温度就变成了随机数。我的问题是,为什么在世界上,预增量工作,但在后增量后,析构函数是被调用的对象?这是我工作前的增量:
Weather &Weather::operator++() {
++ptr->airTemperature;
return *this;
}这是不工作岗位的增加:
Weather Weather::operator++(int) {
Weather temp = *this;
++ptr->airTemperature;
return temp;
}正如我所理解的,预增量本身返回,post增量返回副本,所以我这样做了,但是什么会导致这个问题呢?
发布于 2021-05-10 13:50:55
尝试这样的方法,您可以避免所有复制构造函数和析构函数。
class Temp {
double airTemperature;
};
class Weather {
public:
Weather(std::shared_ptr<Temp> tempPtr)
: ptr(tempPtr){}
std::shared_ptr<Temp> ptr;
Weather Weather::operator++(int) {
Weather temp = *this;
++ptr->airTemperature;
return temp;
}
Weather &Weather::operator++() {
++ptr->airTemperature;
return *this;
}
};当然,考虑一下是否真的需要一个指向临时的指针。也许你应该这么做。
class Weather {
public:
Weather(Temp temp)
: temp(temp){}
Temp ptr;
Weather Weather::operator++(int) {
Weather temp = *this;
++temp.airTemperature;
return temp;
}
Weather &Weather::operator++() {
++temp.airTemperature;
return *this;
}
};https://stackoverflow.com/questions/67471510
复制相似问题