65,183
社区成员




class A
{
public:
A(int i){x=new int;*x=i;}
// A(A&r){x=new int;*x=r.get();}
~A(){delete x;x=NULL;}
void set(int i){*x=i;}
int get(){return *x;}
A operator=(A&r)
{
*x=r.get();
return *this;
}
private:
int *x;
};
||=== Build: Debug in oooo (compiler: GNU GCC Compiler) ===|
|In function 'int main()':|
|error: no match for 'operator=' (operand types are 'A' and 'A')|
|note: candidate is:|
|note: A A::operator=(A&)|
|note: no known conversion for argument 1 from 'A' to 'A&'|
class A
{
public:
A(int i){x=new int;*x=i;cout << "A(int i)operated" << endl;}
// A(A&r){x=new int;*x=r.get();}
~A(){delete x;x=NULL;cout << "~A()operated"<< endl;}
void set(int i){*x=i;}
int get(){return *x;}
A& operator=(A&r)
{
*x=r.get();
return *this;
}
private:
int *x;
};
并且调试这个main函数的时候
int main()
{
A a(1), b(2), c(3); //(1)
a = b = c; //(2)
cout << a.get() << b.get() << c.get(); //(3)
}
我发现在运行完第(3)行输出的时候会跳到(1)然后调用两次析构函数,再重新跳到(3)然后又调用了一次析构函数,我不太懂
#include<iostream>
using namespace std;
class A
{
public:
A(int i){x=new int;*x=i;}
// A(A&r){x=new int;*x=r.get();}
~A(){delete x;x=NULL;}
void set(int i){*x=i;}
int get(){return *x;}
A& operator=(A&r)
{
*x=r.get();
return *this;
}
private:
int *x;
};
int main()
{
A a(1),b(2);
(a=b).set(3);
cout<<a.get()<<endl;
return 0;
}
A a,b,c;
a=b=c;