Here are some speciel operators: The () operator. This operator is declared inside a class like that: return_type operator ()(arguments) and you use it like this: object(arguments) The speciel thing about this operator, is that it can have as many arguments as you want. The casting operator is used to change the type of the object, declared inside a class like this: operator type() The speciel thing about this operator, is that you don't need to write the return type before the "operator" keyword. The compiler knows what the return type is according to the operators name. It is called when you try to put the object inside a variable of a different type, or when you call it directly: (type)object); class Cls
{
private:
int value;
public:
Cls(int v)
{
value=v;
}
operator int()
{
return value;
}
};
void main()
{
int integer=Cls(9);
} Now integer is set to 9. Ofcourse you can put more complex code inside the operator function. The intput/output operators, << and >>, are acting just like the normal operators, but they are the most complex ones. That is because the way you use them. As you remember, with a member(inside a class) operator function, the first operand is the object itself, stored in the variable "this". Lets take a look at this simple printing command: cout<<o; The first operand is cout!!! That means that if o is an object, the operator function can not be a member of o, and it can not use it's private memeber variables, which we want to print!!! So how do we solve the problem? There are three ways: 1)We can supply our class with get and set functions. However, that way, the whole world can have access to it's private members, and we don't want that. 2)We can make the operator function a friend of our class. However, if I will teach you that, and my programing teacher will find it our, she will kill me. I will be killed anyways, since I tought here the goto command, and I don't think I can be killed twice. So this is not an option here. 3)We can supply our class with read/write functions. This will be what we do: #include<iostream.h>
class Cls
{
private:
int value;
public:
Cls(int v)
{
value=v;
}
void write(ostream& ostrm)
{
ostrm<<value;
}
};
ostream& operator<<(ostream& ostrm,Cls cls)
{
cls.write(ostream);
return ostream;
}
void main()
{
cout<<Cls(5);
} You can do the same thing with the input operator >>. The reason the operator function returns ostream& is that it will be possible to chain: cout<<"Cls="<<Cls(5)<<"got that?\n"; That will be all for today. Class dissmissed.