overload cout operator c++ code example
Example 1: c++ overload < operator
struct Record
{
std::string name;
unsigned int floor;
double weight;
friend bool operator<(const Record& l, const Record& r)
{
return std::tie(l.name, l.floor, l.weight)
< std::tie(r.name, r.floor, r.weight);
}
};
Example 2: c++ overload operator
#include <iostream>
class ExampleClass {
public:
ExampleClass() {}
ExampleClass(int ex) {
example_ = 0;
}
int& example() { return example_; }
const int& example() const { return example_; }
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;
std::cout << c3.example();
}