类中的模板方法
Template method inside a class
本文关键字:模板方法 更新时间:2023-10-16
我有一个名为time
的类,它有day
、month
和year
。
我在方法中返回正确的值时遇到问题,根据我们输入的字符串"s"
它应该从这 3 个字段之一返回一个int
值。
因此,例如,如果我想在我的日期中获取天数,我应该调用函数d["day"]
。 我的问题是,我的代码有问题吗?而且,我应该放什么而不是
int operator[] (string s)
{
if (s == "day" || s == "month" || s == "year")
{
return ? ? ? ;
}
}
从解释中,如果我理解正确,您需要以下内容。您需要根据字符串匹配返回适当的成员(即day
或month
或year
(。(假设您有mDay
、mMonth
和mYear
作为Date
类中的int
eger 成员(
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 语句。
相关文章:
- 将成员函数指针作为参数传递给模板方法
- 模板方法访问正向声明的类仅在没有此指针的情况下无法编译
- C++11:模板方法的模板函数调用无法编译?
- 如何从ECS中的模板方法获取组件?
- 使用 SFINAE 设计模板方法
- 一个模板方法,用于同时接受常量和非常量参数
- C++模板方法中的循环依赖关系
- 在 C++ 中使用模板方法重写类方法
- 类中的模板方法
- 基于枚举参数调用专用模板方法
- 模板中的模板方法 - 实例声明和类方法声明签名不同
- 可变参数模板方法
- 使用模板方法为标头提供空 cpp 时出现问题
- SFINAE 方法在 clang 中完全禁用基类的模板方法
- 将函数和成员函数传递给模板方法
- 从非模板类调用专用模板方法
- MSVC使用constexpr-if从可变模板方法中的基本模板参数中吞下const
- 依赖于特定类类型的C++模板方法
- 有没有办法仅在两个模板参数相同时才覆盖匹配的模板方法?
- 如何避免模板方法的循环依赖