Compile time polymorphism using operator overloading
Consider a class distance which stores a distance value using kilometer and meter. Overload the = = operator to check the two distance.
#include <iostream>
class Distance
{
public:
void setDistance(float n, float m)
{
kilometrs = n;
metrs = m;
}
void viewDistance()
{
std::cout << "kilometrs=" << kilometrs << std::endl;
std::cout << "metrs=" << metrs<< std::endl;
}
friend bool operator==(const Distance& n1, const Distance& n2);
Distance() {};
Distance(float n, float m)
{
kilometrs = n;
metrs = m;
}
private:
double kilometrs{ 0 };
double metrs{ 0 };
};
bool operator==(const Distance& n1, const Distance& n2)
{
return n1.kilometrs == n2.kilometrs && n1.metrs == n2.metrs;
}
int main()
{
//example test
Distance d1(10, 200);
Distance d2(150, 200);
Distance d3(150, 200);
std::cout << "View dataset" << std::endl;
std::cout << "d1:" << std::endl;
d1.viewDistance();
std::cout << "d2:" << std::endl;
d2.viewDistance();
std::cout << "d3:" << std::endl;
d3.viewDistance();
std::cout << "View example " << std::endl;
std::cout << "check d1==d2"<< (d1 == d2)<<std::endl;
std::cout<< "check d2==d3" <<(d3==d2)<<std::endl;
return 0;
}
Comments
Leave a comment