返回信息流最近重新看了一下操作符重载,发现还是有很多东西不是很明白。其中有个问题是关于临时对象的。
代码如下:
#include <iostream>
#include <string>
using namespace std;
class Integer
{
int i;
string name;
public:
Integer(int ii, string nm = ""): i(ii), name(nm)
{
cout << "Integer() " << name << ":" << i << endl;
}
Integer(const Integer& v): name(v.name), i(v.i) // copy constructure
{
name += " copy";
cout << "Integer::copy() " << name << ":" << i << endl;
}
~Integer()
{
cout << "~Integer() " << name << ":" << i << endl;
}
const Integer operator+(const Integer& rv) const
{
return Integer(i+rv.i, name + " " + rv.name);
}
const Integer& operator+() const
{
return *this;
}
Integer& operator=(const Integer& right)
{
if( this == &right) return *this;
i = right.i;
name = right.name;
return *this;
}
Integer& operator+=(const Integer& rv)
{
cout << "just in operator+=" << endl;
i += rv.i;
name += rv.name;
cout << "leaving operator+=" << endl;
return *this;
}
Integer& operator++()
{
i++;
name += " ++";
return *this;
}
Integer operator++(int) 是值返回
{
Integer before(i, name);
i++;
return before;
}
void print()
{
cout << this << endl;
//i = 9;
cout << name << ":" << i << endl;
}
};
void add(Integer& a)
{
cout << "\tin add" << endl;
a.print();
cout << "\tquit add" <<endl;
return;
}
int main()
{
cout << "------------------------------------" << endl;
Integer Susan(1, "Susan"), Tom(2, "Tom"), Jack(3, "Jack");
//Jack += Susan + Tom;
cout << "----------before ++ operation-----------" << endl;
(Susan++).print();
cout << "----------after ++ operation------------" << endl;
cout << "------------------------------------" << endl;
return 0;
}
这个代码在vc6下编译通过 且运行也不报错。
我的问题是这样的。operator++(int)的返回值是值传递的。那按照规定的话,这个值是一个临时对象。而临时对象是const的。但是我调用了 print函数,这个函数不是const的。
这个我就不懂了。这样可以么?
这是一条镜像帖。来源:北邮人论坛 / soft-design / #22335同步于 2007/11/18
该镜像源已超过 30 天没有更新,可能在源站已被删除。
SoftDesign机器人发帖
[讨论]改变临时对象 可以么?
hman
2007/11/18镜像同步14 回复
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
是返回了一个临时变量,
但却通过了一个拷贝构造函数给了一个外部的变量。所以临时变量最终还是消失了。
【 在 hman 的大作中提到: 】
: 哦? 何以见得?
我更晕了。我把拷贝函数删掉,还是可以编译和运行的。
不少十分明白你的意思,还请指教下。
而且我感觉临时对象就是从拷贝构造函数来的呀。
【 在 Jarod 的大作中提到: 】
: 是返回了一个临时变量,
: 但却通过了一个拷贝构造函数给了一个外部的变量。所以临时变量最终还是消失了。
删掉?你怎么删啊?
你就是把自己的那个给注掉,也还会有的默认的那个啊
【 在 hman 的大作中提到: 】
: 我更晕了。我把拷贝函数删掉,还是可以编译和运行的。
: 不少十分明白你的意思,还请指教下。
: 而且我感觉临时对象就是从拷贝构造函数来的呀。
可能有的同学 说的临时对象 和我说的临时对象 不是一个概念。
我说的临时对象 是在 Thinking in C++中定义的。在第十章中有介绍。叫temporary object
Integer operator++(int) 是值返回
{
Integer before(i, name); <-call stack上的integer return时析构
i++;
return before;
}
上述的Integer内存被回收了,但还要传递结果,所以生成了临时对象。
int main()
{
Integer Susan(1, "Susan") //main的stack上创建了Integer.
(Susan++).print();//先执行print,后执行++,执行的是main上stack的print?
}
晕...
执行了几次拷贝构造函数?2次?