本文介绍了如何使用重载==运算符将类中的char数组与另一个char数组进行比较?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为Airplane的类,带有一个私有数据成员,这就是一个char数组。

I have a class called Airplane with a private data member thats a char array.

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

我的目标是比较此变量与const char []类型的输入变量是否相等。

my goal is to compare for equality this variable and an input variable of type const char [].

我的重载函数如下:

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
}

我希望能够使用诸如 hello这样的文本变量来创建一个类。然后能够==它到我想比较相等性的任何随机文本。现在,我的代码无法正常工作,它可以运行,然后在控制台中结束,没有任何错误。基本上,我需要与char数组进行比较,其中一个类是内置了重载函数的类,另一个是由用户输入的。谢谢您的帮助。

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. 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. Thank you for any help.

推荐答案

正如@PaulMcKenzie正确地说的那样, char * 不是数组。

As @PaulMcKenzie has rightly said, char* is not an array.

我建议使用 std :: string 代替 char * 以及超载,如下所示:

I suggest using std::string instead of char* as well as in overload as follows:

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;
}

这篇关于如何使用重载==运算符将类中的char数组与另一个char数组进行比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-01 10:04