1#include <iostream>
2#include <string>
3
4class Car
5{
6private:
7 std::string m_make;
8 std::string m_model;
9
10public:
11 Car(const std::string& make, const std::string& model)
12 : m_make{ make }, m_model{ model }
13 {
14 }
15
16 friend bool operator== (const Car &c1, const Car &c2);
17 friend bool operator!= (const Car &c1, const Car &c2);
18};
19
20bool operator== (const Car &c1, const Car &c2)
21{
22 return (c1.m_make== c2.m_make &&
23 c1.m_model== c2.m_model);
24}
25
26bool operator!= (const Car &c1, const Car &c2)
27{
28 return !(c1== c2);
29}
30
31int main()
32{
33 Car corolla{ "Toyota", "Corolla" };
34 Car camry{ "Toyota", "Camry" };
35
36 if (corolla == camry)
37 std::cout << "a Corolla and Camry are the same.\n";
38
39 if (corolla != camry)
40 std::cout << "a Corolla and Camry are not the same.\n";
41
42 return 0;
43}
44
1lass Fred {
2public:
3 // ...
4};
5if
6 // Without operator overloading:
7 Fred add(const Fred& x, const Fred& y);
8 Fred mul(const Fred& x, const Fred& y);
9 Fred f(const Fred& a, const Fred& b, const Fred& c)
10 {
11 return add(add(mul(a,b), mul(b,c)), mul(c,a)); // Yuk...
12 }
13else
14 // With operator overloading:
15 Fred operator+ (const Fred& x, const Fred& y);
16 Fred operator* (const Fred& x, const Fred& y);
17 Fred f(const Fred& a, const Fred& b, const Fred& c)
18 {
19 return a*b + b*c + c*a;
20 }
21#endif