C++中带指针的运算符重载问题
#include<iostream>usingnamespacestd;classnum{public:num(){n=newint;*n=1;cout<<"构造函数执行...
#include<iostream>
using namespace std;
class num
{
public:
num(){n=new int;*n=1;cout<<"构造函数执行"<<endl;}
num(int i){n=new int;*n=i;cout<<"带参数的构造函数执行"<<endl;}
~num(){
delete n;
n=NULL;
cout<<"析构函数执行"<<endl;
}
int get()const{return *n;}
const num operator+(const num&r)
{
cout<<"+运算执行"<<endl;
int *x=new int;
*x=*n+*(r.n);
n=new int;
*n=*x;
return num(*n);
}
private:
int *n;
};
int main()
{
num one(2),two(3),*three=new num;
*three=one+two;
cout<<three->get()<<endl;
return 0;
}
运行结果中,第一个析构函数执行是哪一步执行的?析构函数中delete语句去掉程序才可以输出正确结果5,如何才可以避免上面这种情况(输出随机数字),并且清掉堆中内存? 展开
using namespace std;
class num
{
public:
num(){n=new int;*n=1;cout<<"构造函数执行"<<endl;}
num(int i){n=new int;*n=i;cout<<"带参数的构造函数执行"<<endl;}
~num(){
delete n;
n=NULL;
cout<<"析构函数执行"<<endl;
}
int get()const{return *n;}
const num operator+(const num&r)
{
cout<<"+运算执行"<<endl;
int *x=new int;
*x=*n+*(r.n);
n=new int;
*n=*x;
return num(*n);
}
private:
int *n;
};
int main()
{
num one(2),two(3),*three=new num;
*three=one+two;
cout<<three->get()<<endl;
return 0;
}
运行结果中,第一个析构函数执行是哪一步执行的?析构函数中delete语句去掉程序才可以输出正确结果5,如何才可以避免上面这种情况(输出随机数字),并且清掉堆中内存? 展开
2个回答
展开全部
运算符重载函数有问题, 然后还缺少赋值函数, 主函数中没有释放three
改正后如下:
#include<iostream>
using namespace std;
class num
{
public:
num(){n=new int;*n=1;cout<<"构造函数执行"<<endl;}
num(int i){n=new int;*n=i;cout<<"带参数的构造函数执行"<<endl;}
~num(){
delete n;
n=NULL;
cout<<"析构函数执行"<<endl;
}
int get()const{return *n;}
const num& operator+(const num&r)
{
*(this->n) += *(r.n);
return *this;
}
num& operator=(const num& r)
{
*(this->n) = *(r.n);
return *this;
}
private:
int *n;
};
int main()
{
num one(2),two(3),*three=new num;
*three=one+two;
cout<<three->get()<<endl;
delete three;
return 0;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询