GPIO Pin Operator Overload

#include <iostream>

using namespace std;

// 1. Define the strongly typed enumeration for logic levels
enum class Level { 
    LOW = 0, 
    HIGH = 1 
};

// 2. Define the GpioPin class
class GpioPin {
private:
    Level state; // Internal storage of the pin state

public:
    // Constructor to set the initial level
    GpioPin(Level initial_level) : state(initial_level) {}

    // OVERLOAD: Assignment operator to "write" to the pin
    // Usage: pin = Level::HIGH;
    GpioPin& operator=(Level new_level) {
        this->state = new_level;
        return *this;
    }

    // OVERLOAD: Type conversion operator to "read" the pin as an int
    // Usage: int value = pin; or cout << pin;
    operator int() const {
        return static_cast<int>(state);
    }
};

int main() {
    int init, next;
    
    // Read user input
    if (!(cin >> init >> next)) return 0;

    // Construct the pin with the initial level
    // We use static_cast to turn the int input into our Level enum
    GpioPin pin(static_cast<Level>(init));

    // Perform the write operation using the overloaded = operator
    pin = static_cast<Level>(next);

    // Perform the read operation using the overloaded int conversion
    // cout will automatically trigger operator int()
    cout << pin << endl;

    return 0;
}

Solving Approach

 

 

 

 

Upvote
Downvote
Loading...

Input

0 1

Expected Output

1