向大家请教一个有关C++的很简单的问题。

plizi 2001-09-16 10:08:56
#include <iostream.h>

class D
{
int x,y,z;
public:
D operator = (D t);
friend D operator ++(D &op,int); // postfix
friend D operator ++(D &op); // prefix
void show();
D(int xx=0,int yy=0,int zz=0) // constructor
{x=xx;y=yy;z=zz;}
};

D D::operator=(D t) // 重载 =
{
x=t.x; y=t.y; z=t.z;
return *this;
}

D operator++(D &op,int) // 重载 object++
{

// 要实现 obj1 = obj2++ (把obj2的
// 各成员的值赋给obj1之后,然后再自增)?
// 上面的代码不能完成这个要求。

}

D operator++(D &op) // 重载 ++object
{
++op.x; ++op.y; ++op.z;
return op;
}

void D::show()
{
cout<<x<<","<<y<<","<<z<<"\n";
}

void main(void)
{
D const t;
D a,b,c;

cout<<"a: "; a.show(); // a: 0,0,0
cout<<"b: "; b.show(); // b: 0,0,0
cout<<"c: "; c.show(); // c: 0,0,0
cout<<"a=++c: "; a=++c;
a.show(); // a: 1,1,1
c=t;
cout<<"b=c++: "; b=c++;
b.show(); // b: 1,1,1
// 如何让b等于0,0,0 ?
}
...全文
125 14 打赏 收藏 转发到动态 举报
写回复
用AI写文章
14 条回复
切换为时间正序
请发表友善的回复…
发表回复
plizi 2001-09-21
  • 打赏
  • 举报
回复
我已经成功实现!谢谢大家!


D D::operator++(int) // 重载 object++
{
// 要实现 obj1 = obj2++ (把obj2的
// 各成员的值赋给obj1之后,然后再自增)?
// 上面的代码不能完成这个要求。

three_d temp=*this;
++*this;
return temp;
}
magicblue 2001-09-21
  • 打赏
  • 举报
回复
to:plizi()
no,no,you said is memberwise copy
wondful 2001-09-20
  • 打赏
  • 举报
回复
用成员函数
plizi 2001-09-20
  • 打赏
  • 举报
回复
就是object的各个成员逐个copy 给另外一个Object
LANDFISH 2001-09-19
  • 打赏
  • 举报
回复
请问高手:什么是bitwise copy啊?
magicblue 2001-09-19
  • 打赏
  • 举报
回复
to:plizi()
返回的是temp,temp完成自增了?!自增的是op,不是temp
plizi 2001-09-19
  • 打赏
  • 举报
回复
D D::operator++(D& op, int) //postfix
{
D temp=*this;
op.x++; op.y++; op.z++;
return temp; //还是不对啊,当执行return之后,不论是
//用++op.x,还是用op.x++,这个object的值
//已经完成自增,没有办法把它原来的值先
//赋给其它的对象.

}

iamcobain 2001-09-19
  • 打赏
  • 举报
回复
up
trustme 2001-09-19
  • 打赏
  • 举报
回复
很有深度的问题,我不会,哈哈。
yyhyan 2001-09-19
  • 打赏
  • 举报
回复
gz
jhere 2001-09-19
  • 打赏
  • 举报
回复
好问题
xiterator 2001-09-17
  • 打赏
  • 举报
回复
改正:D D::operator++(D& op, int) //postfix => D D::operator++(int) //postfix成员操作符形式
xiterator 2001-09-17
  • 打赏
  • 举报
回复
D D::operator++(D& op, int) //postfix
{
D temp=*this;
++op.x; ++op.y; ++op.z;
return temp; //利用bitwise copy 把temp 的内容复制到外部,因为之后temp会析构
}

另外,operator++()/operator++(int)即然都要改变操作的对象,也就没有必要采用friend来而设计,直接设计成成员函数即可。
D& D::operator=(const D& t) // 重载 =
{
if (this==&t) return *this; //防止自我赋值做无用功
x=t.x; y=t.y; z=t.z;
return *this;
}

Nepton 2001-09-17
  • 打赏
  • 举报
回复
++重载:

D &D::operator ++(D d,int)
{
D temp=*this;
++op.x; ++op.y; ++op.z;
return temp;
}


69,373

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧