指针与对象

#include "stdafx.h"
#include "iostream"
using namespace std;

class Test
{
public:
	Test();
	~Test();
	void Func(char* c);
};

Test::Test()
{
	cout << "构造对象" << endl;
}

Test::~Test()
{
	cout << "销毁对象" << endl;
}

 void Test::Func(char* c)
{
	cout << "在" << c << "中调用" << endl;
}

 void Function1()
 {
	 Test a;
	 a.Func("Function1");
 }

 void Function2()
 {
	 Test *p = new Test();
	 p->Func("Function2");
 }
int _tmain(int argc, _TCHAR* argv[])
{
	Function1();
	cout << "------------" << endl;
	Function2();
	getchar();
	return 0;
}

分析:

以变量形式创建对象时,函数执行完后自动销毁

以指针形式创建对象时,并没有销毁,因为此时对象仅仅是保存首地址的指针,与实例没有关联,销毁的是与实例关联的 Test*

如果想要销毁,则需要使用delete

所以,指针只负责对象分配和清理内存,与内存中的对象实例并没有关系。


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值