Fortran日期类型双构造器实现与减号运算符重载问题
问题1:运算符重载接口的正确放置位置
你需要把operator(-)的泛型接口声明和t_Date类型、date_substract函数放在同一个模块内,位置在类型定义之后、模块contains语句之前,同时要将operator(-)和t_Date一起设为public导出,示例结构如下:
module mod_date implicit none private ! 导出类型、构造器和重载运算符 public :: t_Date, operator(-) ! 自定义日期类型定义 type :: t_Date integer :: year, month, day end type t_Date ! 双构造器重载接口 interface t_Date module procedure new_t_Date_from_ymd, new_t_Date_from_serial end interface t_Date ! 减号运算符重载接口,放在该位置即可 interface operator(-) module procedure date_substract end interface operator(-) contains ! 构造函数、date_substract函数的具体实现都写在contains之后 function new_t_Date_from_ymd(y,m,d) result(res) integer,intent(in) :: y,m,d type(t_Date) :: res res%year = y res%month = m res%day = d end function new_t_Date_from_ymd function new_t_Date_from_serial(serial) result(res) integer,intent(in) :: serial type(t_Date) :: res ! 序列数转年月日实现逻辑 end function new_t_Date_from_serial function date_substract(d1, d2) result(diff_days) type(t_Date),intent(in) :: d1, d2 integer :: diff_days ! 日期间隔计算逻辑 end function date_substract end module mod_date
调用时只要在作用域内use mod_date,就可以直接用d1 - d2得到间隔天数。
问题2:是否支持输入输出类型不同的运算符重载
完全符合Fortran语法规则,不需要额外适配。
Fortran对运算符重载的唯一限制是参数数量和运算符的原生元数匹配:二元减号是双参数运算符,只要你的重载函数接收2个输入参数,不管参数类型、返回值类型和内置运算符是否一致,都可以正常重载。你需要的「两个t_Date输入、返回整数」的逻辑是完全合法的,和C++的异构重载效果一致,没有语法限制。
绝大多数该场景下的报错都是接口放置位置错误、接口与实现的参数不匹配、运算符未导出导致的。
内容的提问来源于stack exchange,提问作者Olórin
相关产品推荐
相关产品推荐

