有关含指针的类的runtime error问题

有关含指针的类的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 MyString &w){
		if(p==w.p){
			return *this;
		}
		if(p) delete[] p;
		if(w.p){
			p=new char[strlen(w.p)+1];
			strcpy(p,w.p);
		}
		else{
			p=NULL;
		}
		return *this;
	}
	MyString &Copy(const char*w){
		if(p) delete[] p;
		if(w){
			p=new char[strlen(w)+1];
			strcpy(p,w);
		}
		else{
			p=NULL;
		}
		return *this;
	}
	friend ostream& operator<<(ostream &cout,MyString& w){
		cout<<w.p;
		return cout;
	}
};
int main()
{
	char w1[200],w2[100];
	while( cin >> w1 >> w2) { 
		MyString s1(w1),s2 = s1; //=运算符重载 
		MyString s3(NULL);
		s3.Copy(w1); //写Copy函数 
		cout << s1 << "," << s2 << "," << s3 << endl;  //全部输出w1内容 

		s2 = w2; 
		s3 = s2;
		s1 = s3;
		cout << s1 << "," << s2 << "," << s3 << endl;  //全部输出w2内容 
		//重载运算符<< 
	}
}

原则就是,绝对不能把一片内存空间不慎删掉两次!

没写复制构造函数和重载两次=,dev过了。vs显示的是在一个叫做delete_schalar的cpp文件中有一行 _free_dbg(block, _UNKNOWN_BLOCK);的地方中断。

猜你喜欢

转载自blog.csdn.net/weixin_44288817/article/details/88326856