先上两篇文章 再分析自己的:
http://blog.csdn.net/pcliuguangtao/article/details/5990561
C++中赋值和初始化不同“实例说明---欢迎大家发表自己的看法
#include
using namespace std;
class Astring
{
public:
Astring(){s_=NULL;}
Astring(const char *init);
~Astring();
Astring(const Astring &that);
Astring &operator=(const Astring &that);
Astring &operator=(const char *str);
friend ostream& operator<<(ostream&,Astring&);
void swap(Astring &that);
private:
Astring(const char*,const char *);
char *s_;
};
ostream& operator<<(ostream& output,Astring& str)
{
output<<STR.S_<<" n?;
return output;
}
Astring::Astring(const char *init)
{
if(!init) init="";
s_=new char[strlen(init)+1];
strcpy(s_,init);
}
Astring::~Astring()
{delete [] s_;}
Astring &Astring::operator=(const char *str)
{
if(!str) str="";
char *tmp=strcpy(new char[strlen(str)+1],str);
delete [] s_;
s_=tmp;
return *this;
}
int main()
{
Astring *names=static_cast(::operator new(100));
*names="dsfsdsfsd";
cout<<NAMES;
return 0;
}
上面mian函数中*names="dsfsdsfsd";是有问题的,在vs2010里面原因是:
First-chance exception at 0x59eb59da (msvcr100d.dll) in test.exe: 0xC0000005: Access violation reading location 0xcdcdcdc1.
Unhandled exception at 0x59eb59da (msvcr100d.dll) in test.exe: 0xC0000005: Access violation reading location 0xcdcdcdc1. 非法访问内存地址!!!
但是我们已经定义了:Astring &Astring::operator=(const char *str),是因为赋值的时候会先清除左边的目标,然后再进行赋值;但是,我们直接使用的是new:
Astring *names=static_cast(::operator new(100));并没有调用Astring的任何构造函数,即names并没有被初始化,但是*names="dsfsdsfsd"就会先删除*names里面的内容,所以出现错误。
改为下面的就可以了:
int main()
{
Astring names;
names="dsfsdsfsd";
cout<<NAMES;
return 0;
}
其中Astring names会默认调用
Astring(){s_=NULL;}构造函数,已经进行了初始化,所以可以成功的进行赋值。
http://social.msdn.microsoft.com/Forums/en-NZ/vcgeneral/thread/00ff8bf8-df4d-4d5f-ae72-d998165cee26
I have this:
char *something="thisthing"; char buffer[128]={0}; sprintf_s(buffer,128,"%s", something[0]);I get unhandled exception at some memory block. Access violation reading some memory location. The stack frame in VS shows _output_s_l() in output.c breaking at line 1643. Your input will be highly appreciated.
Signature series