类中的模板方法

Template method inside a class

本文关键字:模板方法      更新时间:2023-10-16

我有一个名为time的类,它有daymonthyear

我在方法中返回正确的值时遇到问题,根据我们输入的字符串"s"它应该从这 3 个字段之一返回一个int值。

因此,例如,如果我想在我的日期中获取天数,我应该调用函数d["day"]。 我的问题是,我的代码有问题吗?而且,我应该放什么而不是

int operator[] (string s) 
{
if (s == "day" || s == "month" || s == "year") 
{
return ? ? ? ;
}
}

从解释中,如果我理解正确,您需要以下内容。您需要根据字符串匹配返回适当的成员(即daymonthyear(。(假设您有mDaymMonthmYear作为Date类中的integer 成员(

int operator[] (std::string const& s) 
{
if (s == "day")   return mDay;
if (s == "month") return mMonth;
if (s == "year")  return mYear;
// default return
return -1;
}

或者使用switch语句

// 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

否则,应在运算符中使用 if-else 语句或 switch 语句。