64,632
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
using namespace std;
class test{
public:
int *p;
test(int value){
p = new int(value);
}
~test(){
delete p;
p = NULL;
}
test operator = (const test &pt){
printf("\n test.");
if( p != NULL ){
delete [] p;
p = NULL;
}
p = new int(*pt.p);
memcpy(p,&pt,sizeof(pt));
return *this;
}
friend ostream & operator << ( ostream &os, test &A ){
os << *A.p;
return os;
}
void printvalue(){
cout<<"the value is "<<*p<<endl;
}
};
void func(test &t){
cout<<"in the func value is "<< t <<endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
test t1 = 33;
test t2 = t1;
func(t1);
t2.printvalue();
system("pause");
return 0;
}
#include <iostream>
using namespace std;
class test{
public:
int *p;
test(int value){
p = new int(value);
}
~test(){
delete p;
p = NULL;
}
test(const test &other){
p = new int(*other.p);
}
test operator = (const test &pt){
if( this == &pt ) return *this;
delete p;
p = new int(*pt.p);
return *this;
}
bool operator == (const test &other){
return p == other.p;
}
friend ostream & operator << ( ostream &os, test &A ){
os << *A.p;
return os;
}
void printvalue(){
cout<<"the value is "<<*p<<endl;
}
};
void func(test t){
cout<<"in the func value is "<< t <<endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
test t1 = 33;
test t2 = t1;
t2 = 45;
func(t1);
t1.printvalue();
system("pause");
return 0;
}
test& operator=(const test& pt)
{
if(*this == pt)
{
return *this;
}
p = new int(*(pt.p));
return *this;
}
bool operator==(const test& pt)
{
return p == pt.p;
}
按这个代码调试就不会有问题了。[/quote]
我看错了,要delete自己的p
test& operator=(const test& pt)
{
if(*this == pt)
{
return *this;
}
//C++标准规定可以delete空指针,不用判断是否为空
delete p;
p = new int(*(pt.p));
return *this;
}
test& operator=(const test& pt)
{
if(*this == pt)
{
return *this;
}
p = new int(*(pt.p));
return *this;
}
bool operator==(const test& pt)
{
return p == pt.p;
}
按这个代码调试就不会有问题了。
test t1 = 33;
test t2 = t1;
t2 = 45;
func(t1);
t1.printvalue(); //此时打印会发现值为个很大的负数。
所以对于是否加引用的方法我还是不明白,按理来说,不加引用我只是传入值的,为什么会把t1指针给删掉了呢?奇怪的是虽然它被删掉了,但是析构里面的NULL赋值却未执行。
test(const test &other){
p = new int(*other.p);
}
另外按照各位的方法,先定义了test t2(0);然后在执行t2 = t1;就进入复制函数了。基本要求已经达到。
但是对于楼上的说法:
这个代码编译不过应该再定义operator==
bool operator == (const test& pt)
{
return p == pt.p;
}
[/quote]
我不明白,为什么执行p = NULL,还要重载==呢?
bool operator == (const test& pt)
{
return p == pt.p;
}