Answer to Question #185898 in C++ for VARUN

Question #185898

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


1
Expert's answer
2021-04-28T16:49:39-0400
#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;
}

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