高手们,看看下面的问题?

星之瀚海 2003-06-10 04:58:00
#pragma once
#include <string.h>
#include <iostream.h>
#include <iomanip.h>
class Children
{
char *Name;
int Age;
float Weight;
public:
char *getName(void){ return Name;}
int getAge(void){return Age;}
float getWeight(void){return Weight;}
void prData(void){cout<<Age<<" "<<Name;}
Children(void);
Children(int,float);
Children(char *,int=20,float=45.65);
~Children(void);
Children &operator=(Children &child);
};
Children::Children(void)
{
Name = new char[5];
strcpy(Name,"1234");
Age=0;
Weight=0;
}

Children::Children(int age,float weight)
{
Name = new char[5];
strcpy(Name,"1234");
Age=age;
Weight=weight;
//cout<<*Name;
}

Children::Children(char *name,int age,float weight)
{
Name =new char[strlen(name)+1];
strcpy(Name,name);
Age=age;
Weight=weight;
}
Children::~Children(void)
{
delete Name;
}
Children &Children::operator =(Children &child)
{
Name=new char[strlen(child.getName())+1];
strcpy(Name,child.getName());
Age = child.getAge();
Weight = child.getWeight();
return *this;
}
int main(int argc,char *argv[])
{
Children girl("12345678");
girl.prData();
Children boy=girl;
return 0;
}
上面程序编译正常,运行期最后释放boy.name时报告内存错误,难道是我重载的操作符函数没有写对?解决给分
...全文
39 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
星之瀚海 2003-06-10
  • 打赏
  • 举报
回复
问题已解决,按joachern(程序人生) 的方法,再加一个构造函数即可
Children::Children(Children &child)
{
Name=new char[strlen(child.getName())+1];
strcpy(Name,child.getName());
Age = child.getAge();
Weight = child.getWeight();
}
各位接分
joachern 2003-06-10
  • 打赏
  • 举报
回复
不成!!!
joachern 2003-06-10
  • 打赏
  • 举报
回复
直接在构造含书中加入类的一个参数
child(child aa_child)
{

}
就可哟;
liu_feng_fly 2003-06-10
  • 打赏
  • 举报
回复
把char *Name;
改成std::string Name;
这样就不用自己写operator = 和 copy ctor了,方便又安全,还不用自己管理内存。
windnet 2003-06-10
  • 打赏
  • 举报
回复
就是啊。我发觉,一般编译没出错,而运行是内存出错死掉的程序大多都是释放的问题。
星之瀚海 2003-06-10
  • 打赏
  • 举报
回复
steedhorse(晨星):请问如何写拷贝构造函数?
晨星 2003-06-10
  • 打赏
  • 举报
回复
Children boy=girl;这种形式会调用拷贝构造函数,而你的类中根本没有拷贝构造函数,导致boy没有被安全地构造出来,而析构时删除指针则产生了内存错误。

Children boy;
boy=girl;
这种形式才会调用拷贝运算符,所以在你的程序中,重载的拷贝运算符根本没有派上用场。
北极猩猩 2003-06-10
  • 打赏
  • 举报
回复
要同时重载复制构造函数和operator =
在定义operator =事要先释放原来的资源,还要检测是否是自己给自己付值
hpho 2003-06-10
  • 打赏
  • 举报
回复
Chidren(const Chidren& other){
Name = new char[strlen(other.Name)+1];
strcpy(Name, other.Name);
Age = other.Age;
Weight = other.Weight;
}
hpho 2003-06-10
  • 打赏
  • 举报
回复
Chidren boy = girl//这里不是赋值(assign)而是拷贝构做(copy constror)
joachern 2003-06-10
  • 打赏
  • 举报
回复
Children &boy=girl;
joachern 2003-06-10
  • 打赏
  • 举报
回复
跟踪结果显示,重载 =成功
错误出在申明了两个对象,同时又在上面操作
释放的时候发生问题

69,381

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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