本例子来自于学习视频,不是原创。首先,我们已经知道我们创建类时会有四个默认函数(实际是有6个,具体以后再探究)分别是:(以test类为例子)1.构造函数2.拷贝构造函数3.赋值函数4.析构函数以下是具体应用四个函数的过程的一个经典例子,能让我们更好的理解这四个函数的应用 代码如下:
执行的结果分析:
using namespace std;
class Test
{
private:
int value;
public:
Test()
{
value = 0;
cout << "defult create Test:" << this << endl;
}
Test(int t)
{
value = t;
cout << "Create the Test:" << this << endl;
}
Test (const Test& it)
{
value = it.value;
cout << "Copy create the test:" << this << endl;
}
Test & operator=(const Test& it)
{
value = it.value;
cout << this << " = " << &it << endl;
return *this;
}
~Test()
{
cout << "Destory the Test:" << this << endl;
}
int get_value()
{
return value;
}
};
Test fun(Test tp)
{
int x = tp.get_value();
Test tmp(x);
return tmp;
}
int main()
{
Test t1(10);
Test t2;
//Test t3(); //虽然没错,但是创建不了对象,因为规定是若要
//调用默认的构造函数,则不需要括号,用括号会变成函数声明;
t2 = fun(t1);
cout << "main end!" << endl;
return 0;
}
执行的结果分析:
关键点在于:
1.传递t1给形参时的过程
2.返回tmp实参的过程
后续的补充:
fun()函数并不是最优的方法函数,在空间和时间上进行优化:
<pre name="code" class="cpp">/*1未优化前
Test fun(Test tp)//传值操作浪费时间和空间,所以换为引用
{
int x = tp.get_value();
Test tmp(x);
return tmp;
}
*/
/*2对参数传递的优化
Test fun(const Test& tp)//传值操作浪费时间和空间,所以换为引用
//且由于tp不能改变,我们可以加上const。这样可以明显减少时间空间上
{
int x = tp.get_value();
Test tmp(x);
return tmp;
}
//3对返回值的优化
Test fun(const Test& tp)
{
int x = tp.get_value();
//Test tmp(x);
//return tmp;
return Test(x); //这里直接调用构造函数来进行构造一个无名对象进行传值,
//这样系统就不会再创建一个临时变量来存储对象进行传值操作
}
int main()
{
Test t1(10);
Test t2;
//Test t3(); //虽然没错,但是创建不了对象,因为规定是若要
//调用默认的构造函数,则不需要括号,用括号会变成函数声明;
t2 = fun(t1);
cout << "main end!" << endl;
return 0;
}
//4
Test fun(const Test& tp)
{
int x = tp.get_value();
Test tmp(x);
return tmp;
}
int main()
{
Test t1(10);
Test t2 = fun(t1); //编译器对这里的操作进行了优化
cout << "main end!" << endl;
return 0;
}
*/
//5最优解
Test fun(const Test& tp)
{
int x = tp.get_value();
return Test(x);
}
int main()
{
Test t1(10);
Test t2 = fun(t1); //编译器对这里的操作进行了优化
cout << "main end!" << endl;
return 0;
}
</pre><pre name="code" class="cpp">优化最后结果已经和直接创建对象一样了
构造函数调用两次,析构函数调用两次