Non-member operators

S

saneman

I have declared a binary non-member operator+ in the below class.

class superBob {
public:
superBob(int a) : n(a) {}

int getInt() const {
return n;
}
friend int operator+(int,int);

protected:
int n;
};


I have read that non-member binary operators takes two arguments, but
when compiling I get:

‘int operator+(int, int)’ must have an argument of class or enumerated type


As the error indicates one of the arguments must be of class or
enumerated type. Redefining to:

friend int operator+(const superBob&, int);

compiles without error. But why does one of the arguments have to be of
class or enumerated type?
 
V

Victor Bazarov

saneman said:
I have declared a binary non-member operator+ in the below class.

class superBob {
public:
superBob(int a) : n(a) {}

int getInt() const {
return n;
}
friend int operator+(int,int);

You cannot redefine operators for built-in types. Not allowed.
protected:
int n;
};


I have read that non-member binary operators takes two arguments, but
when compiling I get:

‘int operator+(int, int)’ must have an argument of class or
enumerated type

As the error indicates one of the arguments must be of class or
enumerated type. Redefining to:

friend int operator+(const superBob&, int);

compiles without error. But why does one of the arguments have to be
of class or enumerated type?

Because the operator + for 'int' and 'int' is provided by the
language. You can't change the behaviour of built-in types. Not
allowed.

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top