继续补充C++中的基础概念
这里的堆与栈并不是从程序的角度去区分,而不是数据结构
malloc与new的区别
下面是拷贝构造函数和代码验证
三种调用时机需要特别注意
至于为什么拷贝构造函数的参数一定是引用,大家可以思考一下,这个问题值得探讨,也会加深对拷贝构造函数的理解
#include <iostream>
using namespace std;
class CExample
{
private:
int a;
public:
CExample(int b)
{
a = b;
cout << "creat:" << a << endl;
}
CExample(const CExample & C) //拷贝构造函数
{
a = C.a;
cout << "copy" << endl;
}
~CExample()
{
cout << "delete:" << a << endl;
}
};
void fun1(CExample C) //重点1(对象以值传递方式传入函数参数)
{
cout << "test" << endl;
}
CExample fun2() //重点2(对象以值传递方式从函数返回)
{
CExample t(0);
return t;
}
int main()
{
CExample a(1);
fun1(a);
fun2();
CExample b = a; //重点3(对象需要通过另外一个对象进行初始化)
CExample c(a); //同上
return 0;
}
结果如下: