65,208
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
//#include <string>
using namespace std;
class Str{
public:
Str(){
buf =new char[1];
buf[0]='\0';
};
Str(char* s)
{
buf = new char[strlen(s)];
strcpy(buf,s);
}
Str(const Str& s)
{
buf = new char[strlen(s.buf)];
strcpy(buf,s.buf);
}
Str& oparator =(const Str& s)
{
if(this == &s)return *this;
buf = new char[strlen(s.buf)];
strcpy(buf,s);
return *this;
}
friend ostream& operator << (ostream& out, const Str& str){
return out<<str.buf;
};
~Str()
{
delete []buf;
}
private:
char *buf;
};
int main()
{
Str s="hello world";
Str b=s;
cout<<b<<endl; //出错行,初步认为是操作符<<的重载问题
return 0;
}
#include <iostream>
#include <string>
using namespace std;
class Str;
ostream& operator << (ostream& out, Str& str);
class Str{
public:
Str(char* s)
{
buf = new char[strlen(s)];
strcpy(buf,s);
}
~Str()
{
delete buf;
}
public:
char *buf; //改成了public
};
int main()
{
Str s="hello world";
Str b=s;
cout<<b<<endl; //出错行,初步认为是操作符<<的重载问题
return 0;
}
ostream& operator << (ostream& out, Str& str)
{
return out<<str.buf;
}
这样就可以通过了
using namespace std;
class Str;
ostream& operator << (ostream& out, Str& str); //在此处添加该语句
Str(Str const& rhs); //拷贝构造函数
是的,改过后是可以输出显示“hello world”,但是 同时弹出提示
“HEAP CORRUPTION DETECTED:after normal block (#175) at 0x003278B8
CRT detected that the application wrote to memory after end of heap buffer "
”
我在类里面新添加了 拷贝构造函数如:
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
class Str{
public:
Str(char* s)
{
buf = new char[strlen(s)];
strcpy(buf,s);
}
Str(const Str& r,char* s) //新添加的拷贝构造函数
{
buf = new char[strlen(s)]; // 为新对象重新动态分配空间
*buf = *(r.buf);
strcpy(buf,s);
}
~Str()
{
delete buf;
}
friend ostream& operator << (ostream& out, Str& str);
//private:
public:
char *buf;
};
ostream& operator << (ostream& out, Str& str)
{
return out<<str.buf;
}
int _tmain(int argc, _TCHAR* argv[])
{
Str s="hello world";
Str b=s;
cout<<b<<endl;
return 0;
}
但执行问题依然存在,就是可以执行通过,但提示堆溢出。是不是我写的拷贝构造函数有问题?如何避免“内存泄露了, 多次删除, new [] 和 delete不匹配”的问题?[/quote]
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
class Str{
public:
Str(char* s)
{
buf = new char[strlen(s)];
strcpy(buf,s);
}
Str(const Str& r,char* s) //新添加的拷贝构造函数
{
buf = new char[strlen(s)]; // 为新对象重新动态分配空间
*buf = *(r.buf);
strcpy(buf,s);
}
~Str()
{
delete buf;
}
friend ostream& operator << (ostream& out, Str& str);
//private:
public:
char *buf;
};
ostream& operator << (ostream& out, Str& str)
{
return out<<str.buf;
}
int _tmain(int argc, _TCHAR* argv[])
{
Str s="hello world";
Str b=s;
cout<<b<<endl;
return 0;
}
但执行问题依然存在,就是可以执行通过,但提示堆溢出。是不是我写的拷贝构造函数有问题?如何避免“内存泄露了, 多次删除, new [] 和 delete不匹配”的问题?Str s="hello world";
Str b=s;
没有拷贝构造,内存泄露了, 多次删除, new [] 和 delete不匹配。
就是<<重载问题