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.
A few things
I’m guessing that you used _log instead of log due to the clash with log() in cmath. It is a Very Bad Idea to keep your own classes in the standard namespace for this very reason. Maybe the next version of the standard will provide a _log or Logarithm class?
Wrap your own class in
namespace somename {}and reference it by usingsomename::Logarithm()As others have mentioned already You need to declare your operator overloading as friend. Instead of what you have
log operator+ ( const double b ) const;change it to
and define the function in the namespace scope.
Here is the math for the change of base formula
Coefficient in math means the part that is being multiplied by the log. So if you had
A log_b(x) = y
A is the coefficient, B is the base, and Y is the result (or some other names)