对象的赋值和复制

一.对象赋值语句

要求1.同类型2.赋值后是分离的,互不影响3.通过=来赋值

二.拷贝构造函数

一种特殊的构造函数,其形参是本类对象的引用,作用是:是一个用已经存在的对象去初始化另一个同类的对象

1.缺省的拷贝构造函数

#include<iostream>
using namespace std;
class Point
{
public:
	Point(int a, int b)
	{
		x = a;
		y = b;
		cout << "using normal constructor\n" << endl;
	}
	void print()
	{
		cout << x << " " << y << endl;
	}
private:
	int x, y;
};
int main()
{
	Point p1(30, 40);//定义一个对象并传值给初始化函数
	Point p2(p1);//调用缺省的拷贝构造函数
	Point p3 = p1;//第二种调用方式
	p1.print();p2.print();p3.print();
	return 0;
}

没有自定义拷贝构造函数的话,系统会自动的将一个已存在的对象赋值给新对象(就是通过缺省的拷贝构造函数)

    Point p2(p1);调用缺省的拷贝构造函数
    Point p3 = p1;//第二种调用方式

一前面定要加类名不可分开写

2.自定义拷贝构造函数

#include<iostream>
using namespace std;
class Point
{
public:
	Point(int a, int b)
	{
		x = a;
		y = b;
		cout << "using normal constructor\n" << endl;
	}
    Point(Point&p)//自定义的拷贝构造函数
    {
        x=2*p.x;
        y=2*p.y;
        cout << "using copy constructor\n" << endl;
	void print()
	{
		cout << x << " " << y << endl;
	}
private:
	int x, y;
};
int main()
{
	Point p1(30, 40);//定义一个对象并传值给初始化函数
	Point p2(p1);//调用自定义的拷贝构造函数
	p1.print();p2.print();
	return 0;
}

Point p2(p1);调用自定义的拷贝构造函数

Point p3=p1;第二种方式

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值