首页 新闻 搜索 专区 学院

C++写了两个一个强制转换的函数,结果报错

0
悬赏园豆:5 [已解决问题] 解决于 2014-08-06 13:36

代码如下:

class Student
{
public:
int Age;
char* Name;
Student(int age,char *name)
{
Age=age;
Name=new char[strlen(name)+1];
strcpy_s(Name,strlen(name)+1,name);
}

~Student()
{
if(Name!=NULL)
{
delete[] Name;
Name=NULL;
}
}

};
class Teacher
{
public:
int Age;
char *Name;
Teacher(int age,const char* name)
{
Age=age;
Name=new char[strlen(name)+1];
strcpy_s(Name,strlen(name)+1,name);
}
~Teacher()
{
if(Name!=NULL)
{
delete[] Name;
Name=NULL;
}
}
Teacher(Student& s)
{
Age=s.Age;
Name=new char[strlen(s.Name)+1];
strcpy_s(Name,strlen(s.Name)+1,s.Name);
cout<<"隐形转换函数被调用"<<endl;
}

operator Student()
{
cout<<"强制转换成Student"<<endl;
return Student(Age,Name);

}
};


int _tmain(int argc, _TCHAR* argv[])
{
char name[]="baojun";
char sname[]="SSS";
Teacher T(10,name);

Student S=Student(T);
system("pause");

}

c++
baoj2010的主页 baoj2010 | 初学一级 | 园豆:102
提问于:2014-07-24 15:07
< >
分享
最佳答案
0

1,构造函数里有内存泄漏问题

2,Student S=Student(T);是T转换Student,哪有这个转换

收获园豆:5
kevinzhwl | 菜鸟二级 |园豆:304 | 2014-08-05 15:39

Teacher(Student& s)
{
Age=s.Age;
Name=new char[strlen(s.Name)+1];
strcpy_s(Name,strlen(s.Name)+1,s.Name);
cout<<"隐形转换函数被调用"<<endl;
}

我知道内存泄露,但不知道是哪里泄露的

 

baoj2010 | 园豆:102 (初学一级) | 2014-08-06 13:32

额 太马虎了 我本意是这样的

Student s(10,name);

Teacher T=Teacher(s);

写错了 呵呵

baoj2010 | 园豆:102 (初学一级) | 2014-08-06 13:36
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册