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.
RUNTIME INPUT
3
4
5
6
OUTPUT
not equal
#include <iostream>
class Distance
{
public:
void setDistance(float dkm, float dm)
{
kilometrs = dkm;
metrs = dm;
}
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 dkm, float dm)
{
kilometrs = dkm;
metrs = dm;
}
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(100, 300);
Distance d2(110, 300);
Distance d3(250, 350);
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