C++ operator overload for variables inside class -
I want to add my_Contents (int) of 'left' and 'right' to two square mailboxes.
East.
mailbox (trial); Mailbox (left); Mailbox (right); Left.setSize (10); // my_contents = 10 right.setSize (10); // "" "= 5 test.setSize (5); //" "" = 5 tests = left + right;
However, the class mailbox is not started as a mailbox 'my_contents'. So my code will not run down, so how do I implement operator '+' to apply content in class, which is not used for initialization, as I do?
mailbox operator + (console mailbox and left, const. Mailbox and right) {Mailbox T = mailbox (left.my_Contents + right.my_Contents); Return (t); 1) Call setSize to set the results of my_Contents.
1)
Mailbox Operator + (Constant Mailbox and Left, Constant Mailbox and Right) {ints = left.my_Contents + right.my_Contents; Mailbox T; T.setSize (s); Return T; }
One more thing is that your operator should be a friend of the class mailbox
i.e.
class mailbox {int my_contents; Public: Zero Set Setize (int x); // Any friend mailbox operator + (the custom mailbox and the left, the cool mailbox & amp; rights); };
2) Or if you do not want to make it friends, then a getSize
method
is a mailbox operator + (CONST Mailbox and left, const. Mailbox and right) {int s = left.getSize () + right.getSize (); Mailbox T; T.setSize (s); Return T; }
Where getSize
is a member method
zero getSize () {my_Contents return; }
3) Or you can call it + =
class mailbox {int my_Contents; Public: Mailbox & amp; Operator + = (Constant Mailbox & amp; r) {my_Contents + = r.my_Contents; Return * This; } // whatever else }; Mailbox operator + (Constant Mailbox and left, Constant mailbox and right) {Mailbox T = left; T + = true; Return T; }
Comments
Post a Comment