Given the following class definition, write an appropriate definition for
the member function set:
class Temperature
{
public:
void set(double new_degrees, char new_scale);
//Sets the member variables to the values given as
//arguments.
double degrees;
char scale; //'F' for Fahrenheit or 'C' for Celsius.
};
The definition for the set
member function of the Temperature
class:
PROGRAM CODE:
#include <stdexcept> // Include this header to use std::invalid_argument
class Temperature
{
public:
void set(double new_degrees, char new_scale)
{
// Check if the scale is valid ('F' or 'C')
if (new_scale != 'F' && new_scale != 'C')
{
throw std::invalid_argument("Invalid scale. Use 'F' for Fahrenheit or 'C' for Celsius.");
}
// Assign the new values to the member variables
degrees = new_degrees;
scale = new_scale;
}
double degrees;
char scale; // 'F' for Fahrenheit or 'C' for Celsius.
};
set
member function takes two arguments: new_degrees
(a double
representing the new temperature value) and new_scale
(a char
representing the scale, which can be either 'F' for Fahrenheit or 'C' for Celsius).set
function, we first check if the provided scale is valid ('F' or 'C'). If it is not valid, we throw an exception using std::invalid_argument
to indicate that an invalid scale was provided. Otherwise, we assign the new_degrees
and new_scale
values to the member variables degrees
and scale
, respectively.This set
member function allows you to set the temperature and its scale for an instance of the Temperature
class. For example:
Temperature t;
t.set(75.0, 'F'); // Sets the temperature to 75.0 degrees Fahrenheit