面试题——拷贝构造赋值函数的调用

1、Date对象做参数传值/传引用

//1、Date对象做参数传值/传引用
void f1(Date d)//传值
{}
void f2(Date& d)//传引用
{}
//调用
Date d1;
f1(d1);//传值
f2(d1);//传引用

2、Date对象做返回值传值/传引用

Date ff1()//传值
{
	Date d;
	return d;
}
Date& ff2()//传引用
{
	Date d;
	return d;
}
//调用
Date d21 = ff1();//传值
Date d22 = ff2();//传引用
cout << endl;

3、Date对象做临时返回值传值/传引用(编译器优化)

Date fff1()//传值
{
	return Date();
}
Date fff2()//传引用
{
	return Date();
}
//调用
Date d31;
d31 = fff1();//传值
Date d32;
d32 = fff2();//传引用

#include<iostream>
using namespace std;
class Date
{
public:
	Date()
	{
		cout << "Date()" << endl;
	}
	~Date()
	{
		cout << "~Date()" << endl;
	}
	Date(const Date& d)
	{
		cout << "Date(const Date& d)" << endl;
	}
	Date& operator = (const Date& d)
	{
		cout << "Date& opertor = (const Date& d)" << endl;
		return *this;
	}
};
//1、Date对象做参数传值/传引用
void f1(Date d)//传值
{}
void f2(Date& d)//传引用
{}

//2、Date对象做返回值传值/传引用
Date ff1()//传值
{
	Date d;
	return d;
}
Date& ff2()//传引用
{
	Date d;
	return d;
}
//3、Date对象做临时返回值传值/传引用(编译器优化)
Date fff1()//传值
{
	return Date();
}
Date fff2()//传引用
{
	return Date();
}
void test()
{
	//1、Date对象做参数传值/传引用
	Date d1;
	f1(d1);//传值
	f2(d1);//传引用
	cout << endl;

	2、Date对象做返回值传值/传引用
	Date d21 = ff1();//传值
	Date d22 = ff2();//传引用
	cout << endl;

	3、Date对象做临时返回值传值/传引用(编译器优化)
	Date d31;
	d31 = fff1();//传值
	Date d32;
	d32 = fff2();//传引用
	cout << endl;
}
int main()
{
	test();
	system("pause");
	return 0;
}

例题:计算下列函数调用了几次拷贝构造函数,几次赋值运算符函数?

#include<iostream>
using namespace std;
class AA
{
public:
	AA()
	{
		cout << "AA()" << endl;
	}
	~AA()
	{
		cout << "~AA()" << endl;
	}
	AA(AA& a)
	{
		cout << "AA(AA& a)" << endl;
	}
	AA& operator=(AA& a)
	{
		cout << "AA& operator=(AA& a)" << endl;
		return *this;
	}
};
AA f(AA a)
{
	return a;
}
void test1()
{
	AA a1;
	a1 = f(a1);
}
void test2()
{
	AA a1;
	AA a2 = f(a1);
}
void test3()
{
	AA a1;
	AA a2 = f(f(a1));
}
int main()
{
	test1();
	cout << endl;
	test2();
	cout << endl;
	test3();

	system("pause");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值