【发布时间】:2011-12-04 03:21:41
【问题描述】:
我不确定我的问题是什么。它说“丢弃限定符”。我不知道为什么会这样。如果我删除 const 的重载 operator+= 一切都很好。有人可以帮帮我吗?
// 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
【问题讨论】:
-
¤ 制作纯存取函数
const。例如,制作TotalTimeInSeconds() const。干杯&hth., -
真的@Alf,你应该回去回答。
-
@Xeo 但是到一些技术性更强的网站...