Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Overload question

Status
Not open for further replies.

rocky4279

Programmer
Joined
Apr 10, 2004
Messages
1
Location
US
I am attempting to write a C++ program to overload the ^ operator.

I am attempting to create a class to overload the operator and calculate two integers (base and exponent)

I would appreciate any help in how to approach this.
 
You can overload operator^ to have sweet syntax for power computation. But this operator has wrong precedence for power semantics. For instance : 2 + 3 ^ 2 will be computed as (2 + 3)^2 = 25 instead of 11 -> operator+ has precedence other operator^.
But you can compute the right number with parenthesis : 2 + (3 ^ 2). Using operator^ can be error prone if you forget parenthesis.

--
Globos
 
Here is a basic example I wrote, showing the precedence problem. Maybe there is a workaround about this problem I don't know it.
Code:
#include <math.h>
#include <iostream>

using namespace std;

class Integer
{
public://-- Creation
  //Intialize an Integer object with value 'v'.
  Integer (int v = 0) :
    _value (v)
  {
  }

  //Intialize an Integer object from 'other'.
  Integer (const Integer& other) :
    _value (other.value ())
  {
  }
  
public://-- Access
  //The value hold by this Integer object.
  int value () const
  {
    return _value;
  }

public://-- Element change
  //Assign 'other' to this Integer object.
  Integer& operator= (const Integer& other)
  {
    _value = other.value ();
    return *this;
  }

public://-- Basic operations
  //result = this ^ exponent.
  Integer operator^ (const Integer& exponent) const
  {
    return Integer (pow (_value, exponent.value ()));
  }

  //result = this ^ exponent.
  Integer operator^ (int exponent) const
  {
    return Integer (pow (_value, exponent));
  }

  //result = this + other.
  Integer operator+ (const Integer& other) const
  {
    return Integer (_value + other.value ());
  }

  //TODO: define and implement other operations here.

private://-- Attributes
  int _value;
};

//Print Integer object 'v' on 'stream'.
ostream& operator<< (ostream& stream, const Integer& v)
{
  return stream << v.value ();
}

//result = value + other(make Integer::operator+ symetrical).
Integer operator+ (int value, const Integer& other)
{
  return Integer (value + other.value ());
}


//Test it
int main ()
{
  Integer wrong = 2 + Integer (3) ^ 2;//precedence problem
  Integer right = 2 + (Integer (3) ^ 2);//solved with paranthesis
  cout << "wrong 2 + 3^2 = " << wrong << endl;
  cout << "right 2 + 3^2 = " << right << endl;

  return 0;
}

--
Globos
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top