首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

C++程序设计,该怎么解决

2012-09-25 
C++程序设计#ifndef STRING_H#define STRING_H#include iostream.hclass String{friend ostream & opera

C++程序设计
#ifndef STRING_H
#define STRING_H
#include <iostream.h>
class String
{
  friend ostream & operator<<(ostream &,const String &);

public:
String(const char * ="1");
const String & operator=(const String &);
private:
int length;
char *sptr;
};
#endif



#include <string.h>
#include <iomanip.h>
#include <cstdlib>
#include "String.h"
String::String( const char *ptr)
  :length(strlen(ptr)==0?strlen(ptr):0)
{
cout<<"Conversation constructor:"<<ptr<<endl;
sptr=new char [length+1];
strcpy(sptr,ptr);
}
const String & String::operator=(const String & string)
{
  cout<<"operator=called"<<endl;
if (&string!=this)
{
  delete [] sptr; 
length=string.length;
sptr=new char [length];
strcpy(sptr,string.sptr);
}
else
cout<<"Attempted assigment of a string to itself."<<endl;
  return *this;
}
ostream & operator<<(ostream & output,const String & string)
{
  output<<string.sptr;
  return output;
}





#include <iostream.h>
#include "String.h"
int main()
{
  String str1("happy");
  String str2(" birthday");
  String str3;
  cout<<"Str1 is \""<<str1<<"\";str2 is \""<<str2<<"\";str3 is \""<<str3<<'\"'<<"\n\nThe result of camparing str2 and str1 is:"; 
  cout<<"\n\nTesting !str3:"<<endl;
  cout<<"str3 is empty;assigning str1 to str3:"<<endl;
str3=str1;
cout<<"str3 is \""<<str3<<'\"';
  return 0;
}



这个程序中,重载的=运算符函数中,为什么使用了delete后,运行程序总是弹出对话框终止程序。

[解决办法]

C/C++ code
sptr=new char [length];
[解决办法]
嗯嗯,楼上正解。

热点排行