I'm have a bit problem with operator overloading. I have two classes.
#include <iostream> using namespace std; class Meter; //Forward declaration class Inch{ private: double inches; public: Inch() : inches(0) {} Inch(double i) { inches=i; } friend Inch operator+ (const Meter& m, const Inch& i); void out(){ cout << "Inch:" << inches << "\n"; } double getInches() const { return inches; } }; and
class Meter{ private: double meter; public: Meter() : meter(0) {} Meter(double m) { meter=m; } Meter operator+ (const Inch& i) { return Meter(meter + i.getInches() * 0.0254); } void out(){ cout << "Meter:" << meter; } double getMeter() const { return meter; } }; Inch operator+ (const Meter& m, const Inch& i) { return Inch(m.getMeter()/0.0254 + i.getInches()); } In main I have one of each of these classes. I need to add them together with the order : m + i; So m must be the first object. In order to do that, I used friend function in order to use two objects as a parameter.
Inch i(6.4), resultInch; Meter m(14), resultMeter; i.out(); m.out(); resultMeter = m + i; resultMeter.out(); resultInch = m + i; resultInch.out(); With the above, resultMeter holds the correct value, but when I put resultInch compiler gives the "error no match for bla bla bla".
What am I missing?
InchandMeter, create one classLengthwith member functions to get meters and inches and any other unit. Just my opinion.doubleshould probably be markedexplicit, also use constructor initializer lists to init the member variables. Why isInch operator+ (const Meter& m, const Inch& i)afriend? It's calling public member functions.Meter::operator+should be aconstmember function since it does not modify theMeterobject.