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;
}