| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 615 人关注过本帖
标题:类对象数组 被析够 的时候出现 非法错误
只看楼主 加入收藏
巧克力饼干
Rank: 1
等 级:新手上路
帖 子:17
专家分:0
注 册:2006-3-27
收藏
 问题点数:0 回复次数:3 
类对象数组 被析够 的时候出现 非法错误
#include<iostream>
#include<vector>
using namespace std;
class Student
{
public:
Student();
Student(const char*);
Student(Student&);
char* read() {return _name;}
~Student();
private:
char* _name;
};
Student::Student():_name(0)
{
cout<<"Student Defult Constructing called..."<<endl;
}
Student::Student(const char* name)
{
cout<<"Student Constructing called..."<<name<<endl;
_name = new char[strlen(name) + 1];
strcpy(_name,name);
}
Student::Student(Student& p)
{
cout<<"Student Copying Constrcting called... :"<<p._name<<endl;
_name = new char[strlen(p._name) + 1];
strcpy(_name,p._name);
}
Student::~Student()
{
cout<<"Student Destructing called...: "<<_name<<endl;
delete _name;
}
int main()
{
Student a[3] = {"Jones","Anna","Tom"};
Student b[3];
return 0;
}
怎样才能避免出现这样的情况?
搜索更多相关主题的帖子: 对象 
2006-04-05 22:21
名人
Rank: 1
等 级:新手上路
威 望:1
帖 子:205
专家分:0
注 册:2006-3-3
收藏
得分:0 
以下是引用巧克力饼干在2006-4-5 22:21:00的发言:
#include<iostream>
#include<vector>
using namespace std;
class Student
{
public:
Student();
Student(const char*);
Student(Student&);
char* read() {return _name;}
~Student();
private:
char* _name;
};
Student::Student():_name(0)
{
cout<<"Student Defult Constructing called..."<<endl;
}
Student::Student(const char* name)
{
cout<<"Student Constructing called..."<<name<<endl;
_name = new char[strlen(name) + 1];
strcpy(_name,name);
}
Student::Student(Student& p)
{
cout<<"Student Copying Constrcting called... :"<<p._name<<endl;
_name = new char[strlen(p._name) + 1];
strcpy(_name,p._name);
}
Student::~Student()
{
//cout<<"Student Destructing called...: "<<_name<<endl;//此处打印语句注释掉
delete _name;
}
int main()
{
Student a[3] = {"Jones","Anna","Tom"};
Student b[3];
return 0;
}
怎样才能避免出现这样的情况?

这段程序问题并不是析构的时候出的问题,而是在构造b对象的时候默认构造函数将_name赋值为0也就是空,在析构中的那条打印语句打印_name的时候出错了,因为cout打印语句在打印指向NULL指针的时候就会出错。


未必钱多乐便多,财多累己招烦恼。 清贫乐道真自在,无牵无挂乐逍遥。
2006-04-06 10:15
duyouwu2
Rank: 1
等 级:新手上路
帖 子:8
专家分:0
注 册:2005-3-18
收藏
得分:0 
using namespace std;
请问这个是什么意思啊?
2006-04-06 13:16
名人
Rank: 1
等 级:新手上路
威 望:1
帖 子:205
专家分:0
注 册:2006-3-3
收藏
得分:0 
以下是引用duyouwu2在2006-4-6 13:16:00的发言:
using namespace std;
请问这个是什么意思啊?

使用命名空间,自己去看看书吧。


未必钱多乐便多,财多累己招烦恼。 清贫乐道真自在,无牵无挂乐逍遥。
2006-04-06 13:57
快速回复:类对象数组 被析够 的时候出现 非法错误
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.024502 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved