c++ - 丢弃预选赛

标签 c++ g++

我不太确定我的问题是什么。它说“丢弃限定符”。我不知道为什么会这样。如果我为重载运算符+= 删除 const 一切都很好。有人可以帮帮我吗?

// practice on overloading operators on Time variables
#include <iostream>
using namespace std;

class Time {
 public:
  //constructor
  Time(const unsigned int& day = 0, const unsigned int& hour = 0,
       const unsigned int& minute = 0, const unsigned int& second = 0)
    : day_(day),
      hour_(hour),
      minute_(minute),
      second_(second) {
  }
  Time(const unsigned int& second = 0)
    : day_(0),
      hour_(0),
      minute_(0),
      second_(second) {
  }
  //copy constructor
  Time(const Time& time)
    : day_(time.day_),
      hour_(time.hour_),
      minute_(time.minute_),
      second_(time.second_) {
  }
  //assignment operator
  Time& operator=(const Time& time) {
    day_ = time.day_;
    hour_ = time.hour_;
    minute_ = time.minute_;
    second_ = time.second_;
    return *this;
  }
  //destructor
  ~Time() {} 
  //overloaded operators
  Time& operator+=(const Time& time); 
  Time operator+(const Time& time);
 private:
  unsigned int day_;
  unsigned int hour_;
  unsigned int minute_;
  unsigned int second_;
  void ConvertSecondsToTime();
  unsigned int TotalTimeInSeconds();
};
//main function
int main() {
  return 0;
}
  //overloaded operators
unsigned int Time::TotalTimeInSeconds() {
  return (day_ * 24 * 60 * 60 + 
          hour_ * 60 * 60 +
          minute_ * 60 +
          second_);
}
void Time::ConvertSecondsToTime() {
  while (second_ >= 60) {
    second_ -= 60;
    minute_ += 1;
  }
  while (minute_ >= 60) {
    minute_ -= 60;
    hour_ += 1;
  } 
  while (hour_ >= 24) {
    hour_ -= 24;
    day_ += 1;
  }
}
Time& Time::operator+=(const Time& time) {
  second_ = this->TotalTimeInSeconds() + time.TotalTimeInSeconds();
  ConvertSecondsToTime();
  return *this;
}
Time Time::operator+(const Time& time) {
  Time temp(*this);
  temp += time;
  return temp;
}
                                                                1,3           Top

我的输出是:

time_overloaded_operators.cpp: In member function ‘Time& Time::operator+=(const Time&)’:
time_overloaded_operators.cpp:75: error: passing ‘const Time’ as ‘this’ argument of ‘unsigned int Time::TotalTimeInSeconds()’ discards qualifiers

最佳答案

问题是 TotalTimeInSeconds被声明为禁止通过 const 引用调用它,但随后 operator+=试图在 time 上调用它,这是一个常量引用。

解决方法是声明 unsigned int TotalTimeInSeconds() const; ,它表示可以通过 const 引用(以及通过 const 指针和 const 对象的名称)调用成员函数。

关于c++ - 丢弃预选赛,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8373010/

相关文章:

c++ - hash_map/unordered_map 中的项目顺序是否稳定?

c++ - 为什么我尝试输出一个 UTF-8 字符时得到三个不同的数字?

C++ 模板类 : No instance of constructor matches the argument list

c++ - 海湾合作委员会 4.1.2 : error: integer constant is too large for ‘long’ type

c++ - gcov 函数未执行,但行已执行

c++ - 无法编译不完整的类型;循环依赖

c++ - 参数为 "-S -save-temps"的 gcc 将中间文件放在当前目录中

c++ - 如何估计库函数的使用情况

c++ - 模板程序不断崩溃

c++ - 显示属于树的深度路径的二叉搜索树的节点