Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing Operator Overloading with Logarithms in C++

I'm having some issues with implementing a logarithm class with operator overloading in C++.

My first goal is how I would implement the changeBase method, I've been having a tough time wrapping my head around it.

I have tried to understand the math behind changing the base of a logarithm, but i haven't been able to. Can someone please explain it to me?

My second goal is to be able to perform an operation where the left operand is a double and the right operand is a logarithm object.

Here's a snippet of my log class:

// coefficient: double
// base: unsigned int
// result: double
class _log {

 double coefficient, result;
 unsigned int base;

public:

 _log() {
  base = 10;
  coefficient = 0.0;
  result = 0.0;
 }
 _log operator+ ( const double b ) const;
 _log operator* ( const double b ) const;
 _log operator- ( const double b ) const;
 _log operator/ ( const double b ) const;
 _log operator<< ( const _log &b );

 double getValue() const;

 bool changeBase( unsigned int base );
};

You guys are awesome, thank you for your time.

like image 987
Jacob Relkin Avatar asked Feb 15 '26 14:02

Jacob Relkin


1 Answers

My second goal is to be able to perform an operation where the left operand is a double and the right operand is a logarithm object.

To do this, you need to declare the operator as a non-member function at namespace scope (i.e., not in the definition of _log), e.g.,

_log operator+(const double a, const _log& b);

If you need access to the private members of _log, you can declare it as a friend inside the definition of _log:

friend _log operator+(const double a, const _log& b);

Note that names starting with an underscore (e.g., _log) are reserved to the implementation in the global namespace; if the underscore is followed by a capital letter or another underscore, it is reserved everywhere. It would be a good idea to choose a different class name.

like image 188
James McNellis Avatar answered Feb 18 '26 04:02

James McNellis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!