0
点赞
收藏
分享

微信扫一扫

对象的赋值和复制

扬帆远航_df7c 2024-04-10 阅读 9

一.对象赋值语句

要求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;第二种方式

举报

相关推荐

0 条评论