百思不得其解,求助于各位达人!

hotbee 2009-04-25 11:28:01
#include<iostream>
#include<string>
using namespace std;
class String
{public:
String(){p=NULL;}//定义构造函数
String(char *str){p=str;}//重载构造函数的定义
bool operator>(String &string2);
void display();
private:
char *p;
};

void String::display()
{cout<<p;}

bool String::operator>(String &string2)
{String string1;
if (strcmp(string1.p,string2.p)>0)return true;
else return false;
}

int main()
{String string1="Hello",string2="Bo";
cout<<(string1>string2)<<endl;
}
上面的程序是我写的不用友元函数重载>运算符的程序,编译可以通过无错误提示,但一运行就程序崩溃,无解,茫然!
...全文
91 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
Sou2012 2009-04-25
  • 打赏
  • 举报
回复
学习了
hjjdebug 2009-04-25
  • 打赏
  • 举报
回复
bool String::operator>(String &string2)
{String string1(p);
if (strcmp(string1.p,string2.p)>0)return true;
else return false;
}
见红字,添加(p)
  • 打赏
  • 举报
回复
bool String::operator>(String &string2)
{String string1;
if (strcmp(string1.p,string2.p)>0)return true;
else return false;
}

楼主,你最好在构造函数里new一下,在析构里再delete掉。

string1.p现在是空指针,没有分配内存。
goodname 2009-04-25
  • 打赏
  • 举报
回复
你写的主要是string1使用的是局部变量,所以string1.p是空指针
而strcmp使用空指针则崩溃了。
goodname 2009-04-25
  • 打赏
  • 举报
回复

bool String::operator>(String &string2)
{
if (strcmp(this->p,string2.p)>0)return true;
else return false;
}
deltamaster 2009-04-25
  • 打赏
  • 举报
回复
另外还要注意下构造函数的写法,现在这样的写法不是很好。
一般这样的类需要自定义复制构造函数和赋值运算符函数,否则也会造成问题。
deltamaster 2009-04-25
  • 打赏
  • 举报
回复
改正错误,顺便帮整理一下代码。
以后写好看点啊。

#include <iostream>
#include <string>
using namespace std;

class String
{
public:
String()
{
p = NULL;
}
String(char *str)
{
p = str;
}
bool operator>(String&);
void display();
private:
char* p;
};

void String::display()
{
cout << p;
}

bool String::operator>(String& string)
{
//String string1; 运算符左边的表达式是对象本身
if (strcmp(this->p, string.p) > 0) return true;
else return false;
}

int main()
{
String string1="Hello", string2="Bo";
cout << (string1 > string2) << endl;
return 0;
}
freestyIe 2009-04-25
  • 打赏
  • 举报
回复
可以使用this指针,调用自身对象进行操作,修改如下:
bool String::operator>(String &string2)
{
//String string1;
if (strcmp(this->p,string2.p)>0)return true;
else return false;
}

64,649

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧