这个declearation拖车构造函数有什么不同 [英] What is different between this declearation tow constructor

查看:138
本文介绍了这个declearation拖车构造函数有什么不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Point
{
private:
		int x;
		int y;

public:
Point()
{
	x=y=0;
}
Point(int _x,int _y)
{
	x=_x;
	y=_y;
}
void  Show()
{
	cout<<"X ="<<x<<" ,Y ="<<y<<endl;
}
};
void main()
{
	Point* x=new Point();
	x->Show();
	Point X2;
	X2.Show();
		
	Point* y=new Point(1,2);
	y->Show();
	Point Y2(1,2);
	Y2.Show();
getch();
}



这两种方式有什么不同(使用新的关键词还是不使用它)??


what is different between this two way (use new key word or without it)??

推荐答案

使用 new ,您可以在堆上创建一个对象,并在堆栈上创建指向其对象的指针。如果没有 new new,则在堆栈上创建对象本身。堆栈和堆栈上的对象的工作深入到技术的基础,你需要非常好地理解它,完成任何编程。



-SA
With "new", you create an object on heap, and the pointer to its object on stack. Without "new" new, you create the object itself on stack. The work with objects on stack and on heap lie deep in the fundamentals of the technology, you will need to understand it all extremely well, to do any programming at all.

—SA


使用 new 从堆中分配一块内存,你得到一个指针记忆。这意味着你有责任在一段时间后删除该内存。



语法

With new you allocate a piece of memory from the heap you get a pointer to that memory. That implies that you are responsible for deleting that memory some time later.

The syntax
Point x2;



在堆栈上分配一块内存并用x2变量引用它。当您的函数返回时,将自动释放内存。 (因此你永远不应该返回这样一个堆栈对象的地址!)。



堆栈上的分配比堆上的分配更快。但是,堆栈的大小通常远小于堆的内存。因此,您应该从堆中分配大量内存。


allocates a piece of memory on the stack and refer to it with the x2 variable. When your function returns the memory will automatically be freed. (And hence you should never return the address of such a stack object!).

Allocation on the stack is faster than allocation on the heap. However the size of the stack is usually much smaller than the memory of the heap. Hence you should allocate huge chunks of memory from the heap.


在第一种情况下( new ),您动态为对象分配内存(在堆上)并且你必须明确地删除它(我注释了,因为你没有在代码中删除它)。

在第二种情况下(没有 new ),你正在分配静态内存(在堆栈上)。
In the first case (new) you are dynamically allocating memory (on the heap) for the object and you have to explicitely delete it (I remark it since you did not delete it in your code).
In the second case (without new) you are allocating statically memory (on the stack).


这篇关于这个declearation拖车构造函数有什么不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆