Tuesday, July 14, 2009

Beginner C++ question?

Hi, I'm just learning how to use C++ and I'm having some problems with Objects and plugging variables from one class into another. Right now I'm designing a simple calculator program with various classes, each one associated with seperate operators, example Addition class, subtraction, etc. The driver class(Calculator in this case) will accept 2 values from the user and let him/her decide which operator to perform. If the user chooses to add them together then int Value1 and int Value2 should be forwarded to the Addition class which simply returns the two values after adding them together. My only problem is I'm not entirely sure how to do this, in Java I'm assuming I would say something along these lines. Addition new = Addition(Value1, Value2);. then just, return Addition;





Any ideas?

Beginner C++ question?
You could put the operands into the constructor and instantiate a new Addition each time (as in your example), or reuse a single Addition instance via method setOperands( int left, int right ), or methods setOperandLeft( int value ) setOperandRight( int value ).





In either case, to get the result you could have a method


int getResult()


which would generate the reult and return it.





example usage:


Addition newAddition = new Addition(Value1, Value2);


int result = additionInstance.getResult();


free(newAddition);


return result;


*or, under the reuse scenario:*


additionInstance.setOperands( value1, value2 );


display(additionInstance. getResult())





To really get into the spirit of things, Addition should be a subclass of Operation, or even of BinaryOperation which would be a subclass of Operation. The superClass would fully define the setOperands() methods and would include an abstract of the getResult() method. This would allow you to manipulate Operations in a general manner without knowing which operation was involved in every step.





Java would follow the same layout. Since free() is unnecessary, the first example usage shorthens to:


Addition newAddition = new Addition(Value1, Value2);


return additionInstance.getResult();





Hope this helps
Reply:C and C++ work with "pointers" and references (just C++)...so for your case you MUST make sure you pass your "int" values as "%26amp;Value1" and "%26amp;Value2" and set your param for the function with *Value1 and *Value2 .... or just make your function param as "%26amp;Value1" and "%26amp;Value2" and when the variables get passed in they will be passed by reference.





See this example: http://publib.boulder.ibm.com/infocenter...


No comments:

Post a Comment