如何在 C++ 中将类的实例与 char * 变量进行比较

how can I compare an instance of a class with a char * variable in c++?

本文关键字:char 变量 比较 实例 C++      更新时间:2023-10-16

我需要家庭作业方面的帮助。我需要为停车场编写代码。为了编写它,我需要处理我的类"Parkbox"实例的输入,该类已在堆上和通过另一个类"停车场"创建,并带有#define EMPTY "--------".所以这是我的代码:Parkbox的定义:

class Parkbox{
char *license_plate; // car's license plate
public:
Parkbox(); //Default CTOR
Parkbox(char * ); // CTOR
~Parkbox(); // DTOR
void show();
};
and ParkingGarage:
class ParkingGarage{
Parkbox ***p2parkboxes;

和我的CTOR或ParkingGarage,以便在堆上创建Parkbox实例:

ParkingGarage::ParkingGarage(const int rw,const int clm, const int plns){
        p2parkboxes = new Parkbox **[plns];//points to the floors and make the arraq of p2p same size as number as floors
        for(int p=0;p<plns;p++){
            p2parkboxes[p]= new Parkbox *[plns];//for each Plane creats an array of pointer that is same with the num of rows
            for(int r=0;r<rw;r++)
                p2parkboxes[p][r]= new Parkbox [clm];
        }
    }
void ParkingGarage::find_next_free_parking_position()
{
    for(int f=0;f<dimensions_of_parkhouse[0];f++){
        for(int r=0;r<dimensions_of_parkhouse[1];r++){
            for (int c=0;c<dimensions_of_parkhouse[2];c++){ 
                //p2parkboxes[f][r][c] is the instance of the class Pakbox
                if(p2parkboxes[f][r][c]==EMPTY)
                {
                    next_free_parking_position[0]=p;
                    next_free_parking_position[1]=r;
                    next_free_parking_position[2]=c;
                }
            }
        }
    }
}

在"p2parkboxes[f][r][c]==EMPTY"这一点上,它如何给我错误"没有运算符 "==" 匹配这些操作数",.那么我如何将一个类实例直接与另一个变量(如 EMPTY)进行比较呢?

我不知道我是否对你清楚。但是请帮助我,因为如果我不解决这个问题,我就无法继续完成我的代码。

通常,您只能比较两种相同的类型。使用运算符重载,您可以定义自己的比较运算符来解决此问题。不过,C++默认无法比较两个类。

因此,在您的代码中,您似乎正在将 char* 类型与类类型进行比较。您应该将字符*与另一个字符*进行比较。如果将其视为字符串,则应使用 strcmp 来提高安全性

您必须创建匹配的运算符重载。编译器错误应命名参数,但成员很可能如下所示:

bool Pakbox::operator==(const char *other) {
    return !strcmp(other, this->memberstring);
}

请注意,memberstring必须由持有该批次中内容的实际成员替换。