在课堂内使用运算符过载

Use of operator overloading in structure within class

本文关键字:运算符 课堂      更新时间:2023-10-16

我有一个标头文件,我在其中宣布其中包含结构的类。另外,我还声明了一个超载操作员(!=,将结构)作为此类的成员。我在CPP文件中给出了该操作员的定义。但是我无法访问结构的成员

car.h

class car
{ 
int carsor;
struct model
{
    int id;
    int mode;
}prev,curr;
bool operator !=(const model& model1);
};

car.cpp

#include "car.h"
bool car::operator !=(const model& model1)
{
if((model1.id==model.id)&&(model1.mode==model.mode))
{
    return false;
}
else
{
    return false;
}
}

我遇到的错误是这个

Error   2   error C2275: 'car::model' : illegal use of this type as an expression   

我应该如何访问结构成员?

if((model1.id==model.id)&&(model1.mode==model.mode)) - model是您类的名称,而不是对象的名称。您的对象可以通过this访问,或者您可以在同类中完全省略它。使用if((model1.id==prev.id)&&(model1.mode==prev.mode))previf((model1.id==next.id)&&(model1.mode==next.mode))进行比较以与Next进行比较。

this:

bool car::operator !=(const model& model1)
{

是将汽车与模型进行比较的方法。但是,这是:

bool car::model::operator != (car::model const &other) const
{
  return !(*this == other);
}

是一种比较两个模型的方法(我在这里写了它是car::model的方法,但是如果您愿意,它可能是一个免费的功能。

我还用operator==来写它,因为逻辑几乎总是更容易出现:

bool car::model::operator ==(car::model const &other) const
{
    return (this->id == other.id) && (this->mode == other.mode);
}

这些方法将被声明为:

class car
{ 
    struct model
    {
        int id;
        int mode;
        bool operator==(model const&) const;
        bool operator!=(model const&) const;
        // ...