首页 新闻 会员 周边

C++写的一段代码,不知道什么原因就报错了

0
[已解决问题] 解决于 2017-09-09 12:09
 1 #include "stdafx.h"
 2 #include <stdio.h>
 3 #include <string>
 4 
 5 template<typename T> class IComparable
 6 {
 7 public:
 8     virtual int Compare(T first, T second) = 0;
 9     virtual int CompareTo(T theOther) = 0;
10 };
11 
12 class Person : IComparable<Person>
13 {
14     char* m_lpszName;
15     int m_nAge;
16 public:
17     Person(const char* lpszName, int nAge)
18     {
19         this->m_lpszName = new char(strlen(lpszName));
20         strcpy(this->m_lpszName, lpszName);
21         this->m_nAge = nAge;
22     }
23 
24     ~Person()
25     {
26         delete[] this->m_lpszName;
27     }
28 
29     int Compare(Person first, Person second)
30     {
31         return first.m_nAge==second.m_nAge?0:first.m_nAge>second.m_nAge?1:-1;
32     }
33 
34     int CompareTo(Person another)
35     {
36         return this->m_nAge==another.m_nAge?0:this->m_nAge>another.m_nAge?1:-1;
37     }
38 };
39 
40 int _tmain(int argc, _TCHAR* argv[])
41 {
42     Person *tom = new Person("Tom",13);
43     Person *jason = new Person("Jason",27);
44     if(tom->CompareTo(*jason)>0) printf("Tom is older than Jason\n");
45     if(tom->CompareTo(*jason)==0) printf("Tom is the same age to Jason\n");
46     if(tom->CompareTo(*jason)<0) printf("Tom is youngger than Jason\n");
47 }

执行到第37行程序就报错了,到底是哪里错了?

弹出一个对话框,提示testproject.exe触发了一个断点。

Jason_is_just_a_name的主页 Jason_is_just_a_name | 菜鸟二级 | 园豆:202
提问于:2017-09-08 23:46
< >
分享
最佳答案
0

 在你call `CompareTo`的时候,你浅拷贝了一个新的`Person`,然后当这个新对象被销毁的时候,会调用析构函数,delete了你的内存(m_lpszName)。

解决办法为:

template<typename T> class IComparable
{
public:
    virtual int Compare(const T& first, const T& second) = 0;
    virtual int CompareTo(const T& theOther) = 0;
};

你把参数改为引用,这样在调用Compare的时候就不会有新对象的创建和销毁了。

奖励园豆:5
asahi86 | 菜鸟二级 |园豆:242 | 2017-09-09 09:43

Thanks, 完美地解决了问题. 感谢

Jason_is_just_a_name | 园豆:202 (菜鸟二级) | 2017-09-09 12:08
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册