c++ - 类中的模板方法
问题描述
我有一个名为的类time
,它有day
,month
和year
.
我在我的方法中返回正确的值时遇到问题,它在哪里,取决于我们作为字符串输入的内容,"s"
它应该int
从这 3 个字段之一返回一个值。
因此,例如,如果我想在我的日期中获取天数,我应该调用该函数d["day"]
。我的问题是,我的代码有问题吗?而且,我应该放什么而不是
int operator[] (string s)
{
if (s == "day" || s == "month" || s == "year")
{
return ? ? ? ;
}
}
解决方案
一种较浅的方法是将日期定义为三个元素的数组,而不是声明三个单独的数据成员。
在这种情况下,操作员可以查看以下方式,如下面的演示程序所示。
#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 语句。
推荐阅读
- r - 将用户制作的函数应用于带有其他参数的向量
- reactjs - 我们如何将 Material-UI 中的所有 useStyles 放到一个文件中
- c++ - 带有空白的 std::vector
- google-cloud-platform - 通过 API 列出 Google Cloud 的项目特定区域
- git - 如何重命名拉取请求中使用的 git 分支 Github
- java - 你能帮我使用 ArrayList 获得 MergeSort 的正确输出吗
- wpf - 如何在 WPF TabControl 中修复此行为?
- http - 如何在 NestJS 中使用多个全局拦截器
- java - Scanner.nextInt,NoSuchElementException
- javascript - MermaidJs - 来自某个节点的单击事件错误