Answers for "c++ operator overloading"

C++
1

c++ overload operator

#include <iostream>

class ExampleClass {
  public:
    ExampleClass() {}
  	ExampleClass(int ex) {
      example_ = 0;
    }
    int&       example()        { return example_; }
    const int& example() const  { return example_; }
  	//Overload the "+" Operator
  	ExampleClass operator+ (const ExampleClass& second_object_of_class) {
    	ExampleClass object_of_class;
    	object_of_class.example() = this -> example() + second_object_of_class.example();
    	return object_of_class;
  	}
  private:
  	int example_;
};

int main() {
  ExampleClass c1, c2;
  c1.example() = 1;
  c2.example() = 2;
  ExampleClass c3 = c1 + c2;
  //Calls operator+() of c1 with c2 as second_object_of_class
  //c3 gets set to object_of_class
  std::cout << c3.example();
}
Posted by: Guest on February-06-2021
2

c++ overloaded == operator

#include <iostream>
#include <string>
 
class Car
{
private:
    std::string m_make;
    std::string m_model;
 
public:
    Car(const std::string& make, const std::string& model)
        : m_make{ make }, m_model{ model }
    {
    }
 
    friend bool operator== (const Car &c1, const Car &c2);
    friend bool operator!= (const Car &c1, const Car &c2);
};
 
bool operator== (const Car &c1, const Car &c2)
{
    return (c1.m_make== c2.m_make &&
            c1.m_model== c2.m_model);
}
 
bool operator!= (const Car &c1, const Car &c2)
{
    return !(c1== c2);
}
 
int main()
{
    Car corolla{ "Toyota", "Corolla" };
    Car camry{ "Toyota", "Camry" };
 
    if (corolla == camry)
        std::cout << "a Corolla and Camry are the same.n";
 
    if (corolla != camry)
        std::cout << "a Corolla and Camry are not the same.n";
 
    return 0;
}
Posted by: Guest on June-17-2020
0

overload >> operator c++ in class

ostream& operator<<(ostream& os, node* head)
{
    // Function call to overload the "<<"
    // operator
    print(head);
}
Posted by: Guest on September-21-2021
0

overload the >> operator in c++

istream &operator>>( istream  &input, Class_Name &c )
Posted by: Guest on December-01-2020
0

operator = overloading c++

inline bool operator==(const X& lhs, const X& rhs){ /* do actual comparison */ }
inline bool operator!=(const X& lhs, const X& rhs){ return !(lhs == rhs); }
Posted by: Guest on April-18-2021
1

c++ overload < operator

struct Foo
{
    double val;
    friend bool operator<(const Foo& l, const Foo& r)
    {
      	//Custom comparison for l < r goes here
        return l.val < r.val; 
    }
};
Posted by: Guest on March-16-2021

Browse Popular Code Answers by Language