Some basic help with Operators

First, when do you know that an operator is overloaded? I see some exercises where they ask to overload the += operator. How do you overload, and not-overload it ?! whats the main point ?!



Second, I have an exercise where I should write an operator +=, that adds another object of a class (which is under another class). I usualy do that with a FOR cyclus, but this time time I have no COUNTER.

Here is the code, I hope it explains better:

1
2
3
4
5
6
7
8
9
10
11
12
13
class student
{
private:
	char imepre[50];
	char nasoka[4];
	ispit *is;

public:
	student(char *i="",char *n="")
	{
		strcpy(imepre,i);
		strcpy(nasoka,n);
	}


(ispit *is) , is a dynamic allocated object from another class.
No, I have to write a += operator, which allows a new "IS" object to be added to the curent LIST of IS-es, a list which is empty at the beggining.

I would know to solve this, if there was a previously declared counter, but I can't this way :/
Last edited on
I have not understood the question

First, when do you know that an operator is overloaded?


Either I see the class definition whether it contains overloaded operators or overload an operator if I am going to use it.
I see some exercises require specifically: "these operators should be overloaded: +=, ==, -= etc..

What is the difference between these two:

AirCompany &operator+=(Airplane &ai)
and
void operator+=(Airplane &ai)

I've no idea which should be used where.
Last edited on
It is obvious that they have different return types.:) The first allows associative assignment and can be used in expression because it returns an object.
Oh, I get it now, I missed the "return *this" for the first one, but which one is used when?

I still don't understand why some exercises explicitly require to write an "overloaded operator" and some don't.


Anyways, lets get to the problem now, I need a hand there too.

If I have a declared counter, I would usually do this to add another object to a list of objects:

(notice "BR", it's an INT, that has the curent number of members in "A")


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class AirCompany
{
      Airplane *a;
      int br;

.
.
.

AirCompany &operator+=(Airplane &av)
             {
                     Airplane *t;
                     t=new Airplane[br+1];
                     for(int i=0;i<br;i++)
                     t[i]=a[i];
                     delete [] a;
                     t[br++]=av;
                     a=t;
                     delete [] t;
                     return *this;
             }



But in this execrise, it says that at the beggining the number of objects in "A" is empty. Does this mean that I can manualy declare a COUNTER (like BR) and set it to 0 ?
How should my += operator look in this case?

Last edited on
Topic archived. No new replies allowed.