C++ 类中的模板方法
我有一个叫做C++ 类中的模板方法,c++,function,class,operator-overloading,member,C++,Function,Class,Operator Overloading,Member,我有一个叫做time的类,它有天,月和年 我在方法中返回正确的值时遇到问题,根据我们输入的字符串“s”,它应该从这三个字段之一返回int值 因此,例如,如果我想在日期中获得天数,我应该调用函数d[“day”]。 我的问题是,我的代码有问题吗?还有,我应该用什么来代替 int operator[] (string s) { if (s == "day" || s == "month" || s == "year") { return ? ? ? ; }
time
的类,它有天
,月
和年
我在方法中返回正确的值时遇到问题,根据我们输入的字符串“s”
,它应该从这三个字段之一返回int
值
因此,例如,如果我想在日期中获得天数,我应该调用函数d[“day”]
。
我的问题是,我的代码有问题吗?还有,我应该用什么来代替
int operator[] (string s)
{
if (s == "day" || s == "month" || s == "year")
{
return ? ? ? ;
}
}
根据解释,如果我理解正确,您需要以下内容。您需要根据字符串匹配返回相应的成员(即
日
或月
或年
)。(假设您的Date
类中有mDay
、mMonth
和mYear
作为int
eger成员)
或者使用
一种方法是将日期定义为三个元素的数组,而不是声明三个单独的数据成员 在这种情况下,操作员可以按照下面演示程序中所示的方式进行查看
#include <iostream>
#include <string>
#include <iterator>
#include <algorithm>
#include <stdexcept>
class MyDate
{
private:
unsigned int date[3] = { 26, 12, 2019 };
public:
unsigned int operator []( const std::string &s ) const
{
const char *date_names[] = { "day", "month", "year" };
auto it = std::find( std::begin( date_names ), std::end( date_names ), s );
if ( it == std::end( date_names ) )
{
throw std::out_of_range( "Invalid index." );
}
else
{
return date[std::distance( std::begin( date_names ), it )];
}
}
};
int main()
{
MyDate date;
std::cout << date["day"] << '.' << date["month"] << '.' << date["year"] << '\n';
return 0;
}
否则,应在运算符中使用if-else语句或switch语句 您最好使用标准库作为日期时间逻辑。这个方法也可以作为模板吗?那么应该如何实现呢?所以,如果我想把操作符放在一个泛型方法中。它应该是这样的:模板int操作符[](string const&s){if(s==s)returns;}或者类似的东西
// provide a enum for day-month-year
enum class DateType{ day, month, year};
int operator[] (DateType type)
{
switch (type)
{
case DateType::day: return mDay;
case DateType::month: return mMonth;
case DateType::year: return mYear;
default: return -1;
}
}
#include <iostream>
#include <string>
#include <iterator>
#include <algorithm>
#include <stdexcept>
class MyDate
{
private:
unsigned int date[3] = { 26, 12, 2019 };
public:
unsigned int operator []( const std::string &s ) const
{
const char *date_names[] = { "day", "month", "year" };
auto it = std::find( std::begin( date_names ), std::end( date_names ), s );
if ( it == std::end( date_names ) )
{
throw std::out_of_range( "Invalid index." );
}
else
{
return date[std::distance( std::begin( date_names ), it )];
}
}
};
int main()
{
MyDate date;
std::cout << date["day"] << '.' << date["month"] << '.' << date["year"] << '\n';
return 0;
}
26.12.2019