有关含指针的类的runtime error问题
上课的东西给忘了。一般来说含有指针的类要注意以下几个方面:
要自己写无参构造函数除非是Dev
要自己写复制构造函数,注意的问题和赋值符号的=问题相同,不要随意!切记切记。
要把=号重载,即不仅要根据需要把const char*给对象类型赋值的=号重载,还要把对象之间赋值的=号也重载
一道程序填空题耗费了几个小时,现摘如下:
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
class MyString {
char * p;
public:
MyString(const char * s) {
if( s) {
p = new char[strlen(s) + 1];
strcpy(p,s);
}
else
p = NULL;
}
~MyString() { if(p) delete [] p; }
MyString(){
p=NULL;
}
MyString(const MyString &s){
p=new char[strlen(s.p)+1];
strcpy(p,s.p);
}
MyString &operator=(const char* w){
if(p) delete[] p;
if(w){
p=new char[strlen(w)+1];
strcpy(p,w);
}
else{
p=NULL;
}
return *this;
}
MyString &operator=(const MyStrin