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

标签 c++ char compare instance

我的家庭作业需要帮助。我需要为 parking 场编写代码。为了编写它,我需要将我的类“Parkbox”的实例的输入进行比较,该实例是在堆上创建的,并且是通过另一个类“Parkinggarage”创建的,带有 #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* 类型和您的类类型。您应该将 char* 与另一个 char* 进行比较。如果它被视为字符串,您应该使用 strcmp 以提高安全性

关于c++ - 如何在 C++ 中将类的实例与 char * 变量进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10547329/

相关文章:

c++ - C - 打印 float - 转换为 int 时精度损失

C++ 剪切字符指针

string - 如何测试一个字符串是否包含多个子字符串之一?

c++ - MEX 中 Matlab 和 C++ 之间的内存共享

c++ - Tic Tac Toe 失败的 MiniMax 算法

c++ - 识别未知的鼠标按钮

java - 从 char 数组获取 char 的索引

C++ 字符数组作用域

javascript - jquery组合框比较

python - 比较 CSV 文件中列中的条目并提取匹配项 - python