对象的赋值与复制

对象的赋值与复原理就是把对象作为函数的参数和返回值

1.对象的复制的定义: 

     把对象2的成员变量的值赋给对象1的成员变量的值;

形式:

          对象名1=对象名2;

          或者 类名 对象名1=对象名2;

2.对象复制的定义:用自己已经有的对象重新克隆一个对象;

形式: 

 类名 对象1(对象2);

      或者  类名 对象2=对象1;

伪代码:

            class Stu{

  public:

   int age;

   int no;

........

};

Stu stu1;

stu1.age=30;stu1.no=100;

Stu stu2;

stu2=stu1;  //赋值

Stu stu3=stu1;//复制

 Stu stu4(stu2); //复制

.h文件

#ifndef STU_H
#define STU_H
 
 
class Stu
{
public:
    int age;
    int  no;
    void show();
    Stu();
    Stu(int age,int no);
    ~Stu();
};
 
#endif // STU_H

.cpp文件
#include "stu.h"
#include<iostream>
using namespace std;
Stu::Stu(int age,int no)
{
     cout<<"Stu::stu()"<<endl;
     this->age=age;
     this->no=no;
}
Stu::~Stu()
{
    cout<<"Stu::~Stu()"<<endl;
}
void Stu::show()
{
    cout<<"age="<<age<<"no="<<no<<endl;
}
.main
#include <iostream>
#include"stu.h"
using namespace std;
void f1()
{
     Stu stu1(300,400);
     Stu stu2(30000,40000);
     stu1=stu2;  //对象的赋值,把stu2的值依次赋给stu1
     stu1.show();
}
void f2()
{
    Stu stu1(1,2);
    Stu stu2=stu1;
    stu2.show();
    Stu stu3(stu1);
    stu3.show();
}
f3(Stu stu)//此处是对象的克隆,就是复制了stu1生成了stu,即用stu来显示stu1的值
{
    cout<<&stu<<endl;
}
Stu f4()
{
    Stu stux(1,2);
    return stux;
}
int main(int argc, char *argv[])
{
    Stu stu1(1,2);
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    f1();
     f2();
    //f3(stu1);
   // Stu stu2=f4();//这叫对象的复制
    //Stu stu5;
    //stu5=f4(); //对象的赋值
    cout<<&stu1<<endl;
    cout << "Hello World!" << endl;
    return 0;
}
 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值