C++重载运算符++

标签 c++ operator-overloading

对于一个学校项目,我必须在 C++ 中实现一个传感器类,它有一个私有(private)属性 active( bool 值),它指示传感器是否处于事件状态。 我必须重载++ 运算符,如果使用运算符++,属性 active 将设置为 true。

我实现了以下(sensor.cpp):

Sensor::Sensor(int id, std::string vendor) : _id(id), _vendor(vendor) {
    std::cout << "Sensor created with id: " << Sensor::getId() << std::endl;
    _status = false;
}

bool Sensor::getStatus() {
    return _status;
}

void Sensor::setStatus(bool status) {
    _status = status;
}

Sensor& Sensor::operator++() {
    Sensor result = *this;
    this->setStatus(true);
    return result;
}

主要.cpp:

int main(int argc, char *argv[]) {
    Sensor * sensor = new Sensor(1, "sample vendor");
    sensor->setStatus(false);
    sensor++;
    std::cout << "status: " << sensor->getStatus() << std::endl;
}

我注意到程序停止执行(完成)最后一个要执行的方法 sensor->setStatus(false);在 main.cpp 中,但我的终端没有显示错误,我的编译器也没有提示。

有人知道我做错了什么以及我如何纠正它以便将状态设置为 true 吗?

提前致谢

最佳答案

因为 sensor 是一个指针,sensor++ 递增 pointer 而不是对象。最简单的解决方案是首先不使用指针。

int main() {
    Sensor sensor{1, "sample vendor"};
    sensor.setStatus(false);
    sensor++;
    std::cout << "status: " << sensor.getStatus() << std::endl;
}

另一种解决方案是使用(*sensor)++...

int main() {
    std::unique_ptr<Sensor> sensor =
        std::make_unique<Sensor>(1, "sample vendor");
    sensor->setStatus(false);
    (*sensor)++;
    std::cout << "status: " << sensor->getStatus() << std::endl;
}

您的代码中的另一个错误在这里:

Sensor& Sensor::operator++() {
    // You don't want to do this... it creates a copy!
    Sensor result = *this;
    this->setStatus(true);
    // This is a dangling reference!
    return result;
}

改用这个:

Sensor& Sensor::operator++() {
    this->setStatus(true);
    return *this;
}

关于C++重载运算符++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40454549/

相关文章:

c++ - 箭头-> 运算符重载如何在 C++ 内部工作?

c++ - 不使用模板重载乘法运算符

c++ - 从其他容器中辨别 smart_pointer 的模板函数

c++ - 从一维数组中反转 channel 值

c++ - 无法正确替换字符串中的空格

c++ - 使用getline函数解析c++中的字符串

c++ - 重载 * 运算符 - 必须采用零个或一个参数

c++ - 取消引用运算符不起作用(语法问题?)

c++ - 为什么重载!运营商需要一个常量返回

c++ - 使用 Makefile 运行的程序中出现 Xcode 链接错误