我不太确定我的问题是什么。它说“放弃限定符”。我不知道为什么会发生这种情况。如果我删除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 对象的名称)调用成员函数。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)