如何在 C++ 中将类的实例与 char * 变量进行比较
how can I compare an instance of a class with a char * variable in c++?
我需要家庭作业方面的帮助。我需要为停车场编写代码。为了编写它,我需要处理我的类"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
必须由持有该批次中内容的实际成员替换。
相关文章:
- 如何在保持其值的同时将 c++ 无符号字符变量转换为 char 变量
- 如何更好地检查两个 char 变量是否在一组值中?
- 将双精度值转换为 char 变量时字符串流如何工作
- C++ 如何检查 char 变量是否未定义(未初始化)
- 在 c++ 中将 Char 数组添加到 Char * 变量
- char指针或char变量的默认值是多少
- 当对字符变量使用toupper()时,所述char变量输出多个字符.我该如何防止这种情况发生
- 在C++中,从构造函数中将字符串文本分配给成员const char*变量时会发生什么
- 程序的执行在 C++ 中输入 char 变量后结束
- 如何创建一个 char *[] 变量,以便将其传递给函数
- 将 2 位整数分配给 char 变量
- 将值设置为 char ** 变量 c++ 时出错
- 如果我们在 C++ 中声明一个起始'&'的 char 变量会发生什么?
- 在此范围C 中未声明字符串和char变量
- C++:如何将 char 变量分配给向量<char>并访问该向量的元素进行比较?
- 仅将输入的第一个字符用于 char 变量
- 在C 中使用两个CHAR变量评估布尔值
- 尚未声明char变量
- (C++)如何验证 char 变量的用户输入
- 为什么比较两次 char 变量比比较一次短变量更快