【发布时间】:2019-05-12 09:14:57
【问题描述】:
我重载了 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;
}
【问题讨论】:
-
只需使用
my_string f = "hello";和my_string g = "hello";。为什么你认为那里需要指针? -
my_string* f = "hello";是一个无效的初始化开始。它使f指向包含字符串"hello"的数组的第一个字符。它确实不创建一个新的my_string对象。 -
比较
f==g是比较指针,而不是调用它们可能指向的对象的任何重载函数。
标签: c++ class comparison operator-overloading