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触发了一个断点。
在你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的时候就不会有新对象的创建和销毁了。
Thanks, 完美地解决了问题. 感谢