注册 登录
编程论坛 C++教室

在使用拷贝构造函数的时候出现错误了!

zhiqiang 发布于 2007-12-01 21:13, 855 次点击
编译和连接都没发现错误,在运行的时候弹出一个对话框,错误。
但是我没看出来哪里有错误啊!!
源代码:

#include <iostream.h>
#include <string.h>
class Student
{
  char  *Name;
  int  Age;
public:
  Student(char *namep, int age)
  {
      Age = age;
      if (namep)
      {
         Name = new char[strlen(namep+1)];
         strcpy(Name, namep);
      }
     else
        Name = NULL;
  }
  Student(Student &s)
  {
      Age = s.Age;
      if (s.Name)
      {
         Name = new char[strlen(s.Name)+1];
         strcpy(Name, s.Name);
      }
     else
         Name = NULL;
  }
  void Show()
  {
      cout << Name << ',' << Age << endl;
  }
  ~Student()
  {
      if (Name)
        delete [] Name;
  }
};
void main()
{
  Student  a("George", 20);
  Student  b=a;
  b.Show();
}

[[italic] 本帖最后由 zhiqiang 于 2007-12-1 21:15 编辑 [/italic]]
6 回复
#2
中学者2007-12-01 21:19
Student(Student &s):Name(0)
  {
      Age = s.Age;
      if (s.Name)
      {
         Name = new char[strlen(s.Name)+1];
         strcpy(Name, s.Name);
      }
     else
         Name = NULL;
  }
#3
中学者2007-12-01 21:24
Student(char *namep, int age)
  {
      Age = age;
      if (namep)
      {
         Name = new char[strlen(namep)+1];  //这里
         strcpy(Name, namep);
      }
     else
        Name = NULL;
  }
#4
yuyunliuhen2007-12-01 21:29
#include <iostream>
#include <string>
class Student
{
  char *Name;
  int Age;
public:
  Student(char *namep, int age)
  {
      Age = age;
      if (namep!=NULL)
      {
         Name = new char[strlen(namep)+1];
         strcpy(Name, namep);
      }
     else
        Name = NULL;
  }
  Student(Student &s)
  {
      Age = s.Age;
      if (s.Name!=NULL)                     //
      {
         Name = new char[strlen(s.Name)+1];
         strcpy(Name, s.Name);
      }
     else
         Name = NULL;
  }
  void Show()
  {
      std::cout <<Name << ',' << Age << std::endl;
  }
  ~Student()
  {
      
  }
};
void main()
{
  Student  a("George", 20);
  Student  b=a;
  b.Show();
}

[[italic] 本帖最后由 yuyunliuhen 于 2007-12-1 21:31 编辑 [/italic]]
#5
飞天龙仔2007-12-01 21:34
3楼说的对,
#6
zhiqiang2007-12-01 21:40
回复 3# 的帖子
谢谢大家,我太粗心了!
#7
csmenglei9512007-12-02 19:28
三楼眼神好使,我看了半天都没发现哪个错误..
1