-1

How to define one side operators like ++ or -- in c++?

for example we want to define a## to do (a % 45) + 2 [It is just an example]

  • `##` is a preprocessor directive and can not be overloaded – user7860670 Jun 28 '19 at 07:58
  • 1
    There is no `##` operator in C++. You can't make up custom operators, only [overload predefined operators](https://en.cppreference.com/w/cpp/language/operators). As for `++` and `--`, they are formally known as [increment/decrement operators](https://en.cppreference.com/w/cpp/language/operator_incdec) – Remy Lebeau Jun 28 '19 at 08:00
  • 1
    You can't *add* any operators at all, and you can't overload operators for primitive types. – molbdnilo Jun 28 '19 at 08:22
  • To define `a##`, you'll need to create your own language. Your new language could be C++ like. Creating a language is a big undertaking. Toy languages can take a few months to write; (empirically) industrial strength languages take a decade or more. – Eljay Jun 28 '19 at 11:24
  • The common name for the "one-sided" operators would be **_unary_** operators – MSalters Jun 28 '19 at 14:05

1 Answers1

3

There is operator ++() (prefix increment operator)
and operator ++(int) (postfix increment operator)

Same for 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++;
};

There is no operator ##.

Jarod42
  • 203,559
  • 14
  • 181
  • 302