CRITICAL SKILL 9.2: Assigning Objects 两个对象之间赋值

CRITICAL SKILL 9.2: Assigning Objects 对象之间赋值

If both objects are of the sametype (that is, both are objects of the same class), then one object can beassigned to another. It is not sufficient for the two classes to simply bephysically similar—their type names must be the same. By default, when oneobject is assigned to another, a bitwise copy of the first object’s data isassigned to the second. Thus, after the assignment, the two objects will beidentical, but separate. The following program demonstrates object assignment:

#include <iostream>

using namespace std;

class Test

{

         int a,b;

public:

         voidsetab(int i, intj){a = i, b = j;}

         voidshowab(){

                   cout<<"a is "<< a <<"  b is "<<b <<'\n';

         }

};

int main()

{

         Test ob1, ob2;

         ob1.setab(10, 20);

         ob2.setab(0, 0);

         cout<<"ob1before assignment: ";

         ob1.showab();

         cout<<"ob2before assignment: ";

         ob2.showab();

 

         ob2 = ob1;        //assign ob1 to ob2

         cout<<"ob1after assignment: ";

         ob1.showab();

         cout<<"ob2after assignment: ";

         ob2.showab();

 

         ob1.setab(-1, -1);

         cout<<"ob1after changing ob1: ";

         ob1.showab();

         cout<<"ob2after changing ob1: ";

         ob2.showab();

         return0;

}

Output:

As the program shows, theassignment of one object to another creates two objects that contain the samevalues. The two objects are otherwise still completely separate. Thus, asubsequent modification of one object’s data has no effect on that of theother. However, you will need to watch for side effects, which may still occur.For example, if an object A contains a pointer to some other object B, thenwhen a copy of A is made, the copy will also contain a field that points to B.Thus, changing B will affect both objects. In situations like this, you mayneed to bypass the default bitwise copy by defining a custom assignmentoperator for the class, as explained later in this module.

>>>>>>如果两个对象有相同的类型(就是说,两个都是同一个类的对象),那么一个对象可以赋给另一个对象。两个类在简单的物理上类似是不够的,必须要有相同的类型。默认情况下,当一个对象赋个另一个对象的时候,第一个对象的数据会逐位的拷贝给第二个对象。因此在复制之后,两个对象将会相同,但是在物理上(内存空间)是相互分割的。以下码片演示了对象的赋值:

<<<<<<代码和输出如上所示>>>>>>

       如码片显示,在一个对象给另一个对象赋值的是,所创建的两个对象有包含相同的值。但是两个对象仍然是相互独立的。虽然如此,但还是有副作用出现的情况。如,如果对象A包含指向对象B的指针,那么在对A做拷贝的时候,拷贝的内容将会包含一个指向B的域(指针)。因此,改变B会影响两个对象。在中情况下,应该给类定义一个用户的赋值操作,而不是使用默认的bits位值拷贝。稍后会介绍。

>>>>>>>>>>>>>>>>>>>>>>>translatedby ouyangjun

>>>>>>>>>>>>>>>>>>>>>>>e-mail:ouyangjun1985#msn.com

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值