我的家庭作业需要帮助。我需要为 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/