64,649
社区成员
发帖
与我相关
我的任务
分享
A& operator ++(int) //i++
{
A a(*this);
m++;
return a;
}
以上,a是一个分配在栈上的对象,当函数返回的时候,a将被析构,所以,如果你返回一个引用,不会调用复制构造函数,
那么引用 的将是一个不存在的对象!
A operator ++(int) //i++
{
A a(*this);
m++;
return a;
}
以上,a是一个分配在栈上的对象,当函数返回的时候,a将被析构,但是,你返回的是一个对象,那么会调用复制构造函数,
当函数返回的时候,a被析构,但是复制构造出来的临时对象将被返回!,这个对象,在你的main执行语句中有效,也就是
在(b++).show();这个语句中有效!
#include <iostream>
using namespace std;
class A
{
int n;
int m;
int k;
public:
// A(){};
A(int N=0,int M=0,int K=0):n(N),m(M),k(K){}
A& operator ++() //++i
{
m++;
return *this;
}
A& operator ++(int) //i++
{
A a(*this);
m++;
return a;
}
void Show()
{
cout <<"n=" <<n <<endl <<"m=" <<m <<endl <<"k=" <<k <<endl;
}
};
void main()
{
A a ;
a.Show();
A b(10,20,30);
cout <<endl;
b.Show();
//b++;
cout <<endl;
(b++).Show();
}
/* Result:
n=0
m=0
k=0
n=10
m=20
k=30
n=10
m=20
k=30
Press any key to continue
*/
#include <iostream>
using namespace std;
class A
{
int n;
int m;
int k;
public:
// A(){};
A(int N=0,int M=0,int K=0):n(N),m(M),k(K){}
A& operator ++() //++i
{
m++;
return *this;
}
A operator ++(int) //i++
{
A a(*this);
m++;
return a;
}
void Show()
{
cout <<"n=" <<n <<endl <<"m=" <<m <<endl <<"k=" <<k <<endl;
}
};
void main()
{
A a ;
a.Show();
A b(10,20,30);
cout <<endl;
b.Show();
//b++;
cout <<endl;
(b++).Show();
}
#include <iostream>
using namespace std;
class A
{
int n;
int m;
int k;
public:
// A(){};
A(int N=0,int M=0,int K=0):n(N),m(M),k(K){}
A& operator ++() //++i
{
m++;
return *this;
}
A operator ++(int) //i++ 这里不能返回临时变量,不能用引用
{
A a(*this);
m++;
return a;
}
void Show()
{
cout <<"n=" <<n <<endl <<"m=" <<m <<endl <<"k=" <<k <<endl;
}
};
void main()
{
A a ;
a.Show();
A b(10,20,30);
cout <<endl;
b.Show();
//b++;
cout <<endl;
(b++).Show();
cout<<endl;
(b++).Show(); //为什么此处显示的是 n=--858993460 ;m=--858993460; k=--858993460 这是什么原因呢?
}