简体   繁体   English

此函数如何成为重载运算符?

[英]How can this function be an overloaded operator?

this is a program to convert an object having a string containing a date and another object having 3 ints: date, month and year. 这是一个程序,用于转换一个对象,该对象具有包含日期​​的字符串,而另一个对象具有3个整数:日期,月份和年份。

class date
{
private:
char dt[9];

public: 
//constructors and functions....
};

class dmy
{
private: 
int day,mth,yr;

public:
//constructors..

  operator date()   // This is what my question is about
  {
   char temp[3],str[9]
   itoa(day,str,10)
   strcat(str,"/");
  itoa(mth,temp,10);
  strcat(str,temp)
  strcat(str,"/");
  itoa(yr,temp,10);
  strcat(str,temp);

  return (date(str));
  }

};

int main
{
 date d1;
 dmy d2(17,11,94);

 d1=d2;

 //display d1's and d2's data
 return 0; 
}

My confusion lies in the operator date() part. 我的困惑在于运算符date()部分。 how can date be an operator? 日期如何成为运算符? shouldn't the = operator be overloaded to carry out this conversion? =运算符是否应该重载以执行此转换?

A function of this form of 这种形式的功能

operator T() { /*return an object of type T*/ }

is called user-defined conversion function, which is invoked implicitly when an object of type T is required in any expression. 称为用户定义的转换函数,当任何表达式中都需要T类型的对象时,将隐式调用该函数。

In your case, the user-defined conversion function is defined to implicity convert an object of type dmy into an object of type date . 在您的情况下,用户定义的转换函数被定义为将dmy类型的对象隐式转换为date类型的对象。

void f(date dt);

dmy dmyObj; 

date dateObj = dmyObj; //ok. conversion function is invoked implicitly
f(dmyObj); //ok. conversion function is invoked implicitly
operator date() 

是一个转换函数 ,无论您的代码中什么地方需要date类型,而要使用dmy类型,则将隐式调用此运算符以创建date类型并使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM