What are the uses of the keyword "operator" in c++, I've runned on a couple of definitions but they are not so clear. Can anyone here just give a general idea.
Thanks.
operator keywordwhat are its uses???
Page 1 of 1
4 Replies - 18308 Views - Last Post: 07 December 2007 - 05:06 PM
Replies To: operator keyword
#2
Re: operator keyword
Posted 07 December 2007 - 03:47 PM
C++ allows you to overload operators... That is it allow you to create a custom version of operators such as the + operator. So if I had a class called MyVector and I wanted to define addition for MyVector so that I could use a bit of code like:
MyVector a, b, c;
...
c = a + b;
I can overload the addition operator (+).
Operator overloading
MyVector a, b, c;
...
c = a + b;
I can overload the addition operator (+).
Operator overloading
#3
Re: operator keyword
Posted 07 December 2007 - 03:58 PM
it also allows you to declare conversion operators, which allow safe, implicit casting between classes and other types
for example, if a class had an internal "good" or "bad" state, it might be desirable to be able to evaluate an object inside a conditional statement - This would be a good case for a bool conversion operator
for example, if a class had an internal "good" or "bad" state, it might be desirable to be able to evaluate an object inside a conditional statement - This would be a good case for a bool conversion operator
class myclass
{
bool state;
public:
myclass() : state(true) {}
operator bool()
{
return state;
}
};
int main()
{
myclass mc;
if( mc )
{
// 'state' variable in mc is true
}
}
This post has been edited by Bench: 07 December 2007 - 03:59 PM
#4
Re: operator keyword
Posted 07 December 2007 - 04:06 PM
NickDMax, on 7 Dec, 2007 - 03:47 PM, said:
C++ allows you to overload operators... That is it allow you to create a custom version of operators such as the + operator. So if I had a class called MyVector and I wanted to define addition for MyVector so that I could use a bit of code like:
MyVector a, b, c;
...
c = a + b;
I can overload the addition operator (+).
Operator overloading
MyVector a, b, c;
...
c = a + b;
I can overload the addition operator (+).
Operator overloading
Thanks for the answer and link
#5
Re: operator keyword
Posted 07 December 2007 - 05:06 PM
Bench, on 7 Dec, 2007 - 03:58 PM, said:
it also allows you to declare conversion operators, which allow safe, implicit casting between classes and other types
You know I had COMPLETELY forgotten about that! What is funny is that I saw such a thing not to long ago and sort of squinted at it but it was not until I read your post my memory was jogged and I remembered (if it were not for the example I probably would not have).
Page 1 of 1

New Topic/Question
Reply



MultiQuote



|