我有" my_string "类。我重载了运算符 " == " ,但它不适用于指针 (my_string*)
i have class " my_string ". I overloaded operator " == ", but it doesnt work with pointers (my_string*)
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;
}
这里有几个问题。
首先,如果类型为 string
或 string*
,请致电f == g
时有区别。如果类型是string*
,您实际上并没有比较字符串,而是在比较指针本身(这很少有意义(。如果类型为 string*
,则需要使用 *f == *g
比较它们( *
删除指针,并为您提供指向的实际对象(。
除此之外,这里不需要指针,并且代码my_string* f = "hello"
不应编译。如果您想要指向字符串的指针,则需要使用
my_string str = "hello";
my_string* ptr = &str;
但是,我再也看不出您为什么在这里使用指针。
相关文章:
- cppcheck在const std::string[]上引发警告
- 将std::string传递给WriteConsole API
- 为std::string的某个索引赋值
- std中有类似find_last_of的函数,而string中没有
- 使用 std::string () const 函数启动线程或未来
- 使用char类型将decimal转换为string,将string转换为decimal
- 迭代和比较映射<字符串、矢量<string>> c++ 中的值
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 将向量解析<string>为字符串
- 'string.assign(string.data(), 5)' 是明确定义的还是 UB?
- 如何更改大小(std::string)
- "string.h"在构建适用于iOS的qt应用程序中找不到消息
- C++:如何将 unix 时间的字符串转换为 *tm?(使用时间错误:"cannot convert 'String' to 'tm*' ")
- std::string 的对象真的可以移动吗?
- 与'operator='不匹配(操作数类型'String'且"void")
- SegFault 同时使用 std::string::operator+= 和函数作为参数
- 无法从 std::string 中提取C++ Unicode 符号
- std::string 构造函数如何处理固定大小的 char[]?
- <string> 使用 for 循环写入向量
- C++ My string Has No Effect