1:对象的赋值
如果一个类定义了多个对象,则这些同类的对象之间可以互相赋值,或者说,一个对象的值赋给另一个同类的对象。这里的对象的值是指对象中所有数据成员的值。
2:对象赋值的一般形式
对象名1=对象名2;
(对象1,对象2属于同一个类)
3:例子
#include <iostream>
using namespace std;
class Box
{
public:
Box(int=0,int=0,int=0);//声明有默认参数的构造函数,默认参数可以任意
int volume();
private:
int height;
int width;
int length;
};
Box::Box(int h,int w,int l)//定义构造函数
{
height=h;
width=w;
length=l;
}
int Box::volume()//定义volume函数
{
return(height*width*length);//返回体积
}
int main()
{
Box box1(10,12,14),box2;//定义两个对象
cout<<"the volume of box1 is:"<<box1.volume()<<endl;
box2=box1;
cout<<"the volume of box2 is:"<<box2.volume()<<endl;
return 0;
}
/*the volume of box1 is:1680
the volume of box2 is:1680
Process returned 0 (0x0) execution time : 0.564 s
Press any key to continue.
*/
注意:
类的数据成员中不能包括动态分配的数据,否则赋值将出现严重的后果