Gautam Nath Gautam Nath -4 years ago 152
C++ Question

C++ comparing variables as an object

I'm trying to compare two variables and the type of these variables are "Time". I can't seem to use the == / != function for these.

#include<iostream>
#include "Stock.h"

using namespace std;

void Stock::setShares(int d, int m, int y, int h, int mts, double p, int vol, double val)
{
date.setDate(d, m, y);
time.setTime(h, mts);
price = p;
value = val;
volume = vol;
}

Date Stock::getDate() const
{
return date;
}

Time Stock::getTime() const
{
return time;
}


This is in my main program:

Time t1, t2;
for (int i = 1; i < counter; ++i)
{
if (V1.at(i).getPrice() == highestPrice)
{
time2 = V1.at(i).getTime;
if (time2 != time1)
{
cout << time2;
}
}
}


How can I compare time1 & time2? I'm trying to avoid printing duplicate values of time in my program. V1 is a vector loaded with data from Stock object.

Answer Source

Check first whether == or != operator is overloaded for type Time. You must provide your own meaning to operators which you are gonna to use in your code for user-defined types else you will get compiler errors.

something like below,

class Time
{
public:
      bool operator==(Time const & t1) const
      {
         return this.hour == t1.hour && this.min==t1.min;

      }
private:
     int min;
     int hour;
};
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download