简体   繁体   English

如何使用重载 == 运算符将 class 中的 char 数组与另一个 char 数组进行比较?

[英]How do I compare a char array from a class with another char array using the overload == operator?

I have a class called Airplane with a private data member thats a char array.我有一个名为 Airplane 的 class ,其私有数据成员是一个 char 数组。

// char array variable in my class
char* name{nullptr};

my goal is to compare for equality this variable and an input variable of type const char [].我的目标是比较这个变量和 const char [] 类型的输入变量是否相等。

my overload function looks like this:我的过载 function 看起来像这样:

bool Airplane::operator==(const char input_name[]) const{
    if (this->name == input_name) {
         return true;
     }
return false;
}

By overloading the == operator, I want to be able to do the following:通过重载 == 运算符,我希望能够执行以下操作:

Airplane plane("hello");
if (plane == "hellooo") {
   // do something
}

I want to be able to create a class with a text variable like "hello" and then be able to == it to any random text I want to compare equality.我希望能够使用像“hello”这样的文本变量创建一个 class,然后能够 == 它与我想比较相等性的任何随机文本。 Right now my code just doesnt work, it runs and then ends in the console with no errors.现在我的代码不起作用,它运行然后在控制台中结束,没有错误。 basically I need to compare to char arrays, one within the class the overload function is built in, and another given as input by the user.基本上我需要与 char arrays 进行比较,class 中的一个是内置的过载 function,另一个由用户输入。 Thank you for any help.感谢您的任何帮助。

As @PaulMcKenzie has rightly said, char* is not an array.正如@PaulMcKenzie 所说, char*不是数组。

I suggest using std::string instead of char* as well as in overload as follows:我建议使用std::string代替char*以及overload ,如下所示:

const bool Airplane::operator==(const std::string& str_to_be_compared) const {
    return this->(whatever variable stores the name of the plane) == str_to_be_compared;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM