我不确定我的问题是什么。它说“丢弃限定符”。我不知道为什么会这样。如果我为重载的运算符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
答案 0 :(得分:4)
问题在于TotalTimeInSeconds
被声明为禁止通过const引用调用它,但是operator+=
尝试在time
上调用它,这是一个const引用。< / p>
修复是声明unsigned int TotalTimeInSeconds() const;
,它表示可以通过const引用(以及const指针和const对象的名称)调用成员函数。
答案 1 :(得分:1)
变化:
unsigned int TotalTimeInSeconds();
到
unsigned int TotalTimeInSeconds() const;
因此:
unsigned int Time::TotalTimeInSeconds() {
到
unsigned int Time::TotalTimeInSeconds() const {
基本上说,调用Time
不会修改TotalTimeInSeconds
对象,因此可以将const Time
个对象传递给operator+=
。否则,在Time
内调用TotalTimeInSeconds
时,无法确定operator+=
对象是否会被修改,因此const
限定符被丢弃了。这基本上就是错误的含义。