Stel Team
Stel Team

Reputation: 77

How to change and(&) operator?

as we know & operator used for reference and returning address of a variable. What I want to do is change the operator syntax to something like _ or | (You got the point). How can I do that?

The default:

int *p;
int a;
p = &a;

What I want to do:

int *p;
int a;
p = _a; // or |a

Upvotes: 0

Views: 310

Answers (3)

Bathsheba
Bathsheba

Reputation: 234825

You can't change to _ since that's not an operator, so therefore cannot be overloaded.

You can't change to | since the airity of that operator is binary, whereas pointer dereference * is unary.

Even if you do pick an operator with the correct airity for overloading, note that you cannot overload a built-in type such as int.

Finally if you want to see operator overloading at its most powerful, take a look at this project: http://boost-spirit.com/home/ where expression templates, coupled with operator overloading, are used to mimic EBNF grammars.

Upvotes: 6

Eugene Mart
Eugene Mart

Reputation: 185

& is 'and' when applied to TWO operators, but it is 'take address' when applied unary. You can't possibly confuse them.

If you are just curious you can do this

#include <iostream>
#define _ &


int main()
{
   int a = 5;
   int* p_a = _ a;
   std::cout << *p_a << std::endl;

   return 0;
} 

You have to put a space here. And believe me, nobody wants you redefining standard operators.

Upvotes: 3

Quentin
Quentin

Reputation: 63154

As Bathsheba already answered, you cannot replace operators that easily.

If, however, you really can't stand to use & as an address-of operator, you can use the std::addressof function. It will still be weird and unidiomatic, but at least it makes syntactic sense.

Upvotes: 1

Related Questions