6. Overloading and Operators

6. Overloading and Operators

Postby Cuchulainn » Wed Jan 21, 2009 1:39 pm

We wish to add doubles to complex numbers and complex numbers to doubles:



Complex z1(-23.0, 5.3);

Complex z2(2.0, 3.0);



Complex z3 = z1 * z2;

Complex z4 = 2.0 * z4;



Explain how this code solves the problem:



friend Complex operator * (const Complex& c, double d);

friend Complex operator * (double d, const Complex& c);



Explain
User avatar
Cuchulainn
 
Posts: 668
Joined: Mon Dec 18, 2006 2:48 pm
Location: Amsterdam, the Netherlands

Postby Cuchulainn » Sun Feb 01, 2009 12:42 pm

Can the following 'operators' be overloaded and where would they be used;



*

()

[]

%

&

.

->

^
User avatar
Cuchulainn
 
Posts: 668
Joined: Mon Dec 18, 2006 2:48 pm
Location: Amsterdam, the Netherlands

Postby ImplicitScheme » Tue Nov 16, 2010 7:56 pm

You can overload all of the operators you mentioned except .









You can also overload them in a number of ways. You can define exponentiation via ^ however this would be a bit strange to another programmer. Similarly you can overload (). For example you could make a call option object with private data member Strike and use the () operator to return the price like this



CallOption::operator () (double Spot) const

{

return (Spot > Strike) ? Spot- Strike : 0 ;

}
ImplicitScheme
 
Posts: 6
Joined: Thu Nov 04, 2010 7:01 pm

Postby Cuchulainn » Wed Nov 17, 2010 12:33 am

Yes, '.' cannot be overloaded.



Regarding () this is used as function objects in STL.



BTW did you know , can be overloaded? Here is some cool code in Boost:



vector<int> myVec;

myVec += 10,11,45,80,23,99;

BOOST_ASSERT(myVec.size() == 6);
User avatar
Cuchulainn
 
Posts: 668
Joined: Mon Dec 18, 2006 2:48 pm
Location: Amsterdam, the Netherlands

Postby ImplicitScheme » Wed Nov 17, 2010 3:45 am

I was aware that it could be overloaded only because I happen to know which operators can't be.



Your code is equal parts of interesting and cool. Is there more information about Boost on your website anywhere ?
ImplicitScheme
 
Posts: 6
Joined: Thu Nov 04, 2010 7:01 pm

Postby Cuchulainn » Wed Nov 17, 2010 8:09 am

The boost examples are here



http://www.datasimfinancial.com/forum/v ... .php?t=111



This may also be of interest



www.datasim-press.com
User avatar
Cuchulainn
 
Posts: 668
Joined: Mon Dec 18, 2006 2:48 pm
Location: Amsterdam, the Netherlands

Re: 6. Overloading and Operators

Postby sabahat » Tue Nov 11, 2014 9:13 am

How would you implement a sparsed matrix using just the standard STL containers?
sabahat
 
Posts: 1
Joined: Tue Nov 11, 2014 8:59 am


Return to C++ Certification and Examinations: Intermediate Level

Who is online

Users browsing this forum: No registered users and 1 guest

cron