c++无参构造函数(栈和堆的区别)

1.自定义类型

#include <iostream>
using namespace std;
class Test
{
public:
	Test() {
		cout << "T constructor" << endl;
	}
	~Test() {
		cout << "T destructor" << endl;
	}
		
	
};

Test t2()
{
	Test *p3 = new Test;
	cout << "t2 function" << endl;
	return *p3;
}


int main()
{
	cout << "heap" << endl; //堆对象 的无参构造 函数 2者都可以
	Test *p = new Test();
	delete p;
	p = nullptr;

	Test *p2 = new Test;
	delete p2;
	p2 = nullptr;

	cout << endl;
	cout << "stack" << endl;
	Test t1;
	cout << "t1 end" << endl;
	Test t2();   //此时带括号的 只是做了一个声明  函数返回值是一个Test的对象 ,函数名字为t2  ps:一般是讲其写到其他文件 然后在此处声明,此时仅做演示
	t2();
	cout << "t2 end" << endl;

	return 0;
}

所以 Test t2()不会被认作无参构造函数,只是函数声明,不然会有二义性

2.基础类型

new 只会申请空间,加上小括号后才会初始化为0(可能有些编译器 会优化为0,不过我们还是需要自己加,不要依赖编译器)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值