demo_object_new_delete_1.cpp

来自「对于一个初涉VC++的人来书」· C++ 代码 · 共 65 行

CPP
65
字号

//***************************************************
// new根据参数匹配的原则调用构造函数。 
//***************************************************

# include <iostream.h>
# include <stdlib.h>
# include <conio.h>

class Point
{
public:
	Point()
	{
		X=Y=0;
		cout<<"Default Constructor called."<<endl;
	}

	Point(int xx,int yy)
	{
		X=xx;
		Y=yy;
		cout<< "Constructor called."<<endl;
	}

	~Point()
	{
		cout<<"Destructor called."<<endl;
    }

	int GetX() { return X; }
	int GetY() { return Y; }

	void Move(int x,int y) { X=x; Y=y; }

private:
	int  X,Y;
};

int main()
{
	cout<<"Step One:"<<endl;
	Point *Ptr1=new Point; // new调用无形参构造函数
	if(Ptr1==NULL)
	{
		cout<<"Can't allocate more memory,terminating.\n";
		exit(1);
	}
	getch();
    delete  Ptr1;   

	cout<<endl;
    cout<<"Step Two:"<<endl;
    Ptr1=new Point(1,2); // new调用有形参构造函数
	if(Ptr1==NULL)
	{
		cout<<"Can't allocate more memory,terminating.\n";
		exit(1);
	}
	getch();
    delete Ptr1;

    return 0;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?