Monrelle Monrelle - 22 days ago 6
C++ Question

Classes. Can someone tell me if I did this exercise correctly?

I am trying to create a Temperature class based on these instructions:

Consider a class called Temperature. This class consists of a double called degrees and a string called type. This class has a default constructor. The class also has a constructor taking arguments that only takes an argument for the degrees variable. It has an accessor called get_temperature() that returns a double. It has an overloaded bool operator < that takes as an argument another Temperature object T. It also has a mutator member function called set_type that takes as an argument a string and returns nothing. Write the declaration for the class Temperature. Use the const keyword when appropriate.

#include <iostream>
#include <string>
#include <time.h>

using namespace std;

class Temperature {
public:
Temperature (double degrees_x){
double degrees = degrees_x;
}
void set_type(string type_x){
string type = type_x;}
double get_temperature() const;
bool operator < (Temperature T) const;
private:
double degrees;
string type;


};

Answer
    #include <iostream>
#include <string>
#include <time.h>

using namespace std;

class Temperature {
    //no need to declare private members as private, the default is private
    double degrees;
    string type;
public:
    Temperature (double degrees_x){
        degrees = degrees_x;
    }
    //when setting the type, using 'set_type(string type_x) is inefficient, as type_x will be copied if given an l-value, and then copied again into 'type'
    //getting 'type_x' as const& will make sure you make a single copy, which is in 'string type = type_x' when the copy assigment of the class 'string' is called
    void set_type(const string& type_x){
        string type = type_x;
    }
    double get_temperature() const;
    //the most reasonable thing to do, as already mentioned, is passing T as const&, since you probably won't modify the second operand when checking if T1<T2
    bool operator < (const Temperature &T) const;
};