这样的代码在win2000下调试的通,但是不能运行。

yesman 2002-02-09 05:51:07
#include <iostream>
class firstclass
{
public:
char* name;
};
int main(int argc, char *argv[])
{
firstclass first;
cin >>first.name;
return 0;
}

我运行他给我报错,
...全文
16 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
wanggou 2002-02-09
  • 打赏
  • 举报
回复
class firstclass
{
public:
firstclass(){name = new char[255];}
~firstclass(){delete [] name;}
char* name;
friend ostream& operator<<(ostream& os,firstclass& ft)
{
os<<ft.name;
return os;
}
friend istream& operator>>(istream& is,firstclass& ft)
{
is>>ft.name;
return is;
}
};


int main(int argc, char *argv[])
{
using namespace std;

firstclass first;

cin >> first;

cout << first <<endl;;

return 0;
}
dragondwy 2002-02-09
  • 打赏
  • 举报
回复
指针初始化
下面的代码试试


#include <iostream>

class firstclass
{
public:
firstclass(){name = new char[255];}
~firstclass(){delete [] name;}
char* name;
};


int main(int argc, char *argv[])
{
using namespace std;

firstclass first;

cin >> first.name;

cout << first.name;

return 0;
}
artman 2002-02-09
  • 打赏
  • 举报
回复
name指向的地址不可预测。
artman 2002-02-09
  • 打赏
  • 举报
回复
每给name分配空间。
lifanxi 2002-02-09
  • 打赏
  • 举报
回复
来晚一步,同意楼上各位。
你类中的指针没有指到有效的内存空间,你直接就用了,往里面写字符串,当然要出错了。因此,在构造函数中要用new给他分配空间,才能用它,当然就得用析构函数把空间delete掉了。

15,440

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 非技术区
社区管理员
  • 非技术区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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