184. Hardware Monitor

Back To All Submissions
Previous Submission
Next Submission
#include <iostream>
#include <string>

class TemperatureSensor {
private:
    int raw_adc_value;

    // The 'friend' keyword grants the global function access to private members
    friend void debugMonitor(const TemperatureSensor& s);

public:
    // Constructor initializes the sensor value to 0
    TemperatureSensor() : raw_adc_value(0) {}

    // Public method to update the internal state
    void update(int val) {
        raw_adc_value = val;
    }
};

/**
 * Global function implementation.
 * Because it is a friend of TemperatureSensor, it can access s.raw_adc_value 
 * even though that variable is private.
 */
void debugMonitor(const TemperatureSensor& s) {
    std::cout << "Debug: Raw ADC = " << s.raw_adc_value << std::endl;
}

int main() {
    TemperatureSensor sensor;
    int N;
    
    // Read the number of operations
    if (!(std::cin >> N)) return 0;

    for (int i = 0; i < N; ++i) {
        std::string cmd;
        std::cin >> cmd;

        if (cmd == "READ") {
            int val;
            if (std::cin >> val) {
                sensor.update(val);
            }
        } else if (cmd == "DEBUG") {
            // Call the friend function to peek into the private data
            debugMonitor(sensor);
        }
    }
    
    return 0;
}

Solving Approach

 

 

 

 

Was this helpful?
Upvote
Downvote