C++ C++;将变量作为对象进行比较

C++ C++;将变量作为对象进行比较,c++,C++,我试图比较两个变量,这些变量的类型是“时间”。我似乎不能使用==/!=这些功能 #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);

我试图比较两个变量,这些变量的类型是“时间”。我似乎不能使用==/!=这些功能

#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;
}
#包括
#包括“Stock.h”
使用名称空间std;
无效股票:集合股票(整数d、整数m、整数y、整数h、整数mts、双p、整数vol、双val)
{
日期。设定日期(d,m,y);
时间。设定时间(h,mts);
价格=p;
值=val;
体积=体积;
}
日期库存::getDate()常量
{
返回日期;
}
时间存量::getTime()常量
{
返回时间;
}
这是我的主要节目:

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;
                }
            }
        } 
时间t1,t2;
对于(int i=1;i<计数器;++i)
{
if(V1.at(i).getPrice()==最高价格)
{
time2=V1.at(i).getTime;
如果(时间2!=时间1)
{

请先检查
=
!=
运算符是否对类型
时间
重载。您必须为要在代码中用于用户定义类型的运算符提供自己的含义,否则会出现编译器错误

像下面这样

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

      }
private:
     int min;
     int hour;
};

为了能够完整地回答您的问题,有必要了解“Time”类型的详细信息。既然您谈到比较两个对象,那么我们假设它是class

如果是这样的简单类:

class Time {
    public:
        int getValue();
        void setValue(int value);
    private:
        int value;
}
您需要使用getValue方法:

if( t1.getValue() == t2.getValue())
如果要直接比较对象,需要重载必要的运算符:

bool operator==(const Time& anotherTime) const {
    return (anotherTime.getValue()==this->getValue());
}

什么是
Time
?你试过(或
!=
操作符)这个类吗?Time.h是一个单独的类,我在其中初始化小时、分钟等。
time2=V1.at(I).getTime;
它被编译了吗?那是一个输入错误:)我做了
time2=V1.at(I).getTime();
取而代之。为什么不简单地执行
返回小时==t1.hour&&min==t1.min
?不需要三元表达式。@GautamNath注意,对于不等式运算符
!=
,您不需要实现完整的逻辑,只需将等式运算符与逻辑not运算符
结合使用,就像
返回!(*此==其他对象)
。对于像上面这样简单的东西,这并不重要,但对于比较逻辑更复杂的对象,重用相等运算符将使其更简单。@JoachimPileborg你是对的……不需要?:在上面的代码中,常量对象不能使用
==
-找出原因!@Ajay我无法理解你的意思?你是指什么n在上面的代码中,我们不能使用
==
运算符来比较当前对象和通过常量引用传递的对象?我没有发现这是非法的原因?如果
不需要
,只需执行
返回getValue()==另一个时间。getValue()
就足够了。