C++ 重载运算符的高端用法 operator Type() vs Type operator()

居家隔离中在github上找代码看着玩,偶然看到switch和nds的ftp服务代码,其中我发现那波日本人好像很喜欢重载隐式转换,然后顺手写一个笔记。
先引入一点点ftpd的代码:

namespace fs
{
/// \brief File I/O object
class File
{
public:
	/// \brief bool cast operator
	explicit operator bool () const {
	    return static_cast<bool> (m_fp);
	}

	/// \brief std::FILE* cast operator
	operator std::FILE * () const {
	  return m_fp.get ();
	}
    ...

private:
	/// \brief Underlying std::FILE*
	std::unique_ptr<std::FILE, int (*) (std::FILE *)> m_fp{nullptr, nullptr};
    ...
};

class SockAddr
{
public:
	/// \param sockaddr_in cast operator
	operator struct sockaddr_in const & () const {
	  assert (m_addr.ss_family == AF_INET);
	  return reinterpret_cast<struct sockaddr_in const &> (m_addr);
	}

	/// \param sockaddr_storage cast operator
	operator struct sockaddr_storage const & () const;

	/// \param sockaddr* cast operator
	operator struct sockaddr * ();
	/// \param sockaddr const* cast operator
	operator struct sockaddr const * () const;
    ...

private:
	/// \brief Address storage
	struct sockaddr_storage m_addr = {};
};

int operator()operator int()举例

int operator()是一个函数调用运算符,它将对象转换为可以像函数一样调用的函数对象。返回int。
例如:

struct Struct1 {
  int operator()(int a, int b) { return a + b; }
};
...

Struct1 param;
int i = param(1, 2);  // Call the object as a function, and it returns 3 (1+2)

operator int()是转换运算符。这个特定的类型允许对象隐式(如果声明为显式,则显式)转换为int。它必须返回int(或者无论使用什么类型,也可以使用用户定义的类型,如类或结构)。
例如:

struct Struct2 {
  operator int() { return 666; }
};
...

Struct2 param;
int i = param;  // Calls the conversion operator, which returns 666
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

歪锅锅

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值