我有" my_string "类。我重载了运算符 " == " ,但它不适用于指针 (my_string*)

i have class " my_string ". I overloaded operator " == ", but it doesnt work with pointers (my_string*)

本文关键字:string my 不适用 适用于 指针 运算符 重载 我有      更新时间:2023-10-16

i超载operator ==,并且它不适用于指针

class my_string { 
    private:
        char* _ch;
        int _length;
    public:
                ...
                ...
        bool operator ==(const my_string& right) {
            if (this->_length == right._length) {
                for (int i = 0; i < this->_length; i++) {
                    if (_ch[i] != right._ch[i]) {
                        return false;
                    }
                }
            }
            else
                return false;
            return true;
        }
};
int main(){
my_string* f = "hello";
my_string* g = "hello";
if(f==g){
   cout<<"done";
}
return 0;
}

这里有几个问题。

首先,如果类型为 stringstring*,请致电f == g时有区别。如果类型是string*,您实际上并没有比较字符串,而是在比较指针本身(这很少有意义(。如果类型为 string*,则需要使用 *f == *g比较它们( *删除指针,并为您提供指向的实际对象(。

除此之外,这里不需要指针,并且代码my_string* f = "hello"不应编译。如果您想要指向字符串的指针,则需要使用

my_string str = "hello";
my_string* ptr = &str;

但是,我再也看不出您为什么在这里使用指针。