编译能通过,但运行出问题,请大虾们指点!
#include <iostream>
#include <cstring>
using namespace std;
class preDate{
int mo,da,yr;
char* month;
public:
preDate(int,int,int);
preDate(const preDate& dt);
~preDate();
void display()const;
};
preDate::preDate(int m,int d,int y)
{
cout < <"构造.," < <endl;
char* mos[]={"January","ebruary","March","April","May","June","July","August"
,"September","October","November","December"};
mo=m;
da=d;
yr=y;
if(mo!=0){
month=new char[strlen(mos[mo-1]+1)];
strcpy(month,mos[mo-1]);
}
else month=0;
}
preDate::~preDate()
{
cout < <"析构.." < <endl;
delete[] month;
}
void preDate::display()const
{
cout < <month < <"/" < <*month < <"/" < <da < <"/" < <yr < <endl;
}
preDate::preDate(const preDate& dt)
{
cout < <"构造2.," < <endl;
mo=dt.mo;
da=dt.da;
yr=dt.yr;
if(mo!=0){
month=new char[strlen(dt.month)+1];
strcpy(month,dt.month);
}
else mo=0;
}
//以上是preDate.h文件
// preDate.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include"preDate.h"
int main(int argc, char* argv[])
{
preDate today(5,23,2008);
preDate otherday(today);
preDate lastday=today;
today.display();
otherday.display();
lastday.display();
return 0;
}
//以上是preDate的cpp文件
编译通过并能运行,但运行后出现如下对话框:
Debug Error!
Program:D:\c++程序\preDate\Debug\preDate.exe
DAMAGE:after Normal block(#46)at0X00371B20.(Press Retry debug the application)
终止(A) 重试(R) 忽略(I)
但我把析构函数中的delete[] month;去掉,问题解决!
请大虾们指点!
[解决办法]
strcpy后要写上终止符号,或者你用strncpy
delete[] month出错,只有一个原因,month溢出,无法释放