【发布时间】:2021-12-25 06:54:02
【问题描述】:
#include <string>
#include <tuple>
#include <stdexcept>
using namespace std;
class Date
{
public:
Date() {};
Date(int new_year, int new_month, int new_day)
{
year = new_year;
if ((new_month < 1) || (new_month > 12))
{
throw runtime_error("Month value is invalid: " + to_string(new_month));
}
month = new_month;
if ((new_day < 1) || (new_day > 31))
{
throw runtime_error("Day value is invalid: " + to_string(new_day));
}
day = new_day;
}
int GetYear() const
{
return year;
}
int GetMonth() const
{
return month;
}
int GetDay() const
{
return day;
}
private:
int year;
int month;
int day;
};
bool operator < (const Date &lhs, const Date &rhs)
{
auto lhs = tie(lhs.GetYear(), lhs.GetMonth(), lhs.GetDay());
auto rhs = tie(rhs.GetYear(), rhs.GetMonth(), rhs.GetDay());
return lhs < rhs;
}
我正在尝试创建一个用于存储日期(年、月、日)的类。为了在地图中使用这个类,我想重载比较运算符。不幸的是,上面的代码不起作用。编译器给我一个错误
error: cannot bind non-const lvalue reference of type 'int&' to an rvalue of type 'int'|
错误显然发生在tie 函数中。一旦我将其更改为make_tuple,一切都会编译并运行。我还检查了如果我将变量 year、month 和 day 声明为 public,我可以写类似
auto lhs = tie(lhs.year, lhs.month, lhs.day);
这也可以。
我不明白为什么。有人有想法吗?
【问题讨论】:
-
我现在无法阅读代码,但从您提到的错误来看 - 将引用绑定到非
const临时是不行的。
标签: c++ class c++11 tuples member-functions