You are on page 1of 4

OPERATOR <<

class MyClass {
private:
int value;
public:
MyClass(int num) : value(num) {}
friend std::ostream& operator<<(std::ostream& os, const MyClass& obj) {
os << "Value: " << obj.value; // Customize the output format
return os;
}
};
OPERATOR >>
friend std::istream& operator>>(std::istream& is, MyClass& obj) {
is >> obj.value; // Read the input value into obj.value
return is;
OPERATOR +=
MyClass& operator+=(const MyClass& other) {
value += other.value; // Perform addition and assignment
return *this;
}
OPERATOR -=
MyNumber& operator-=(const MyNumber& other) {
value -= other.value;
return *this;
}
OPERATOR == / < / > / <= / >=
bool operator==(const MyNumber& other) const {
return value == other.value;
}

OPERATOR =
MyNumber& operator=(const MyNumber& other) {
if (this != &other) {
value = other.value;
}
return *this;
}
OPERATOR ++ / --
MyClass& operator++() {
++value;
return *this;
}
OPERATOR += FOR ADDING ELEMENT IN A DYNAMICALLY ALLOCATED ARRAY

#include <iostream>

class FirstClass {
private:
int value;

public:
FirstClass(int val) : value(val) {}

int getValue() const {


return value;
}
};

class SecondClass {
private:
FirstClass** array; // Array of dynamically allocated FirstClass objects
int size; // Size of the array

public:
SecondClass(int n) : size(n) {
array = new FirstClass*[size];
for (int i = 0; i < size; i++) {
array[i] = nullptr;
}
}

void operator+=(FirstClass* element) {


// Create a new array with increased size
FirstClass** newArray = new FirstClass*[size + 1];

// Copy the existing elements to the new array


for (int i = 0; i < size; i++) {
newArray[i] = array[i];
}

// Add the new element at the end


newArray[size] = element;

// Delete the old array


delete[] array;

// Update the array pointer and size


array = newArray;
size++;
}

OPERATOR -= FOR ADDING ELEMENT IN A DYNAMICALLY ALLOCATED ARRAY

#include <iostream>

class FirstClass {
private:
int value;

public:
FirstClass(int val) : value(val) {}

int getValue() const {


return value;
}
};

class SecondClass {
private:
FirstClass** array; // Array of dynamically allocated FirstClass objects
int size; // Size of the array

public:
SecondClass(int n) : size(n) {
array = new FirstClass*[size];
for (int i = 0; i < size; i++) {
array[i] = nullptr;
}
}

void operator-=(FirstClass* element) {


// Find the element in the array
int index = -1;
for (int i = 0; i < size; i++) {
if (array[i] == element) {
index = i;
break;
}
}

// If the element was found, remove it


if (index != -1) {
// Create a new array with reduced size
FirstClass** newArray = new FirstClass*[size - 1];
// Copy the elements before the removed element
for (int i = 0; i < index; i++) {
newArray[i] = array[i];
}

// Copy the elements after the removed element


for (int i = index + 1; i < size; i++) {
newArray[i - 1] = array[i];
}

// Delete the old array


delete[] array;

// Update the array pointer and size


array = newArray;
size--;
}
}

You might also like