【问题标题】:How to define one side operators in c++? [duplicate]如何在 C++ 中定义一侧运算符? [复制]
【发布时间】:2019-11-10 04:19:20
【问题描述】:

如何在 c++ 中定义像 ++-- 这样的一侧运算符?

例如我们想定义a## 来做(a % 45) + 2 [只是一个例子]

【问题讨论】:

  • ## 是预处理指令,不能重载
  • C++ 中没有## 运算符。你不能组成自定义运算符,只有overload predefined operators。至于++--,正式名称为increment/decrement operators
  • 你不能添加任何操作符,你不能为原始类型重载操作符。
  • 要定义a##,您需要创建自己的语言。您的新语言可能类似于 C++。创建一种语言是一项艰巨的任务。玩具语言可能需要几个月的时间来编写; (根据经验)工业级语言需要十年或更长时间。
  • “单面”运算符的通用名称是 unary 运算符

标签: c++ struct operators


【解决方案1】:

operator ++()(前缀自增运算符)
operator ++(int)(后缀自增运算符)

operator -- 也一样。

class Example
{
public:
   int a = 0;

   Example& operator++() { a = (a % 45) + 2; return *this; } // ++ex;
   Exampleoperator++(int) { Example tmp = *this; ++(*this); return tmp; } // ex++;
};

没有operator ##

【讨论】:

    猜你喜欢
    • 2011-01-19
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 2020-05-10
    • 1970-01-01
    • 2011-09-01
    • 1970-01-01
    • 2013-11-07
    相关资源
    最近更新 更多