Answer to Question #181890 in C++ for VARUN

Question #181890

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.


1
Expert's answer
2021-04-15T23:21:18-0400


#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS