一小段程序求助啊
#include<iostream>
#include<string>
using namespace std;
class String
{
char *p;
public:
String(const char *str)
{
int n=strlen(str);
p=new char[n+1];
strcpy(p,str);
}
friend bool operator < (const String &s1,const String &s2)
{
if(strcmp(s1.p,s2.p)==-1)
return true;
return false;
}
friend ostream& operator << (ostream& out, String &str)
{
int n=strlen(str.p);
for(int i=0;i<n;i++)
{
out<<str.p[i];
}
return out;
}
String& operator = (String str)
{
delete []p;
p=new char[strlen(str.p)+1];
strcpy(p,str.p);
return *this;
}
~String()
{
delete []p;
}
};
template<class T>
T maxn(T a[],int n)
{
int i;
for(i=1;i<n;i++)
if(a[0]<a[i]) a[0]=a[i];
return a[0];
}
int main()
{
//int a[]={1,4,2,5,6,7,3,0,8,9};
//double b[]={1.2,2.1,3.2,4.5,1.3,5.6,3.1};
char *p[]={"abc","bcd","cda","bdb","ddd"};
String temp("Empty");
String s[]={String(p[0]),String(p[1]),String(p[2]),String(p[3]),String(p[4])};
temp=maxn(s,5);//这句是怎么一回事啊
//cout<<maxn(a,10)<<endl;
//cout<<maxn(b,7)<<endl;
cout<<temp<<endl;
return 0;
}
出现了异常啊,就是我标明的那一句,我调试了一下好像某个类的对象析构函数执行了两次,求解啊
[解决办法]
汗,写错了,看了下楼主代码,应该是加上我带那个拷贝构造函数就可以了
[解决办法]
函数的返回值不在函数作用域里,所以temp=maxn(s,5);中给temp赋值的是一个临时变量,那么这个临时变量肯定是由复制构造函数构造出来的,临时变量销毁时导致了a[0]的成员指针成野指针。
C++ Primer说过,对于复制构造和赋值操作符,如果需要其中一个,几乎也肯定需要另一个。