动态创建对象举例

动态内存分配

动态申请内存操作符 new

  • new 类型名T(初始化参数列表)

  • 功能:在程序执行期间,申请用于存放T类型对象的内存空间,并依初值列表赋以初值。

  • 结果值:成功:T类型的指针,指向新分配的内存;失败:抛出异常。

释放内存操作符delete

  • delete 指针p

  • 功能:释放指针p所指向的内存。p必须是new操作的返回值。

本题给出了前缀,本题程序,应该和下列代码等价!

6-16 动态创建对象举例

#include <iostream>

using namespace std;

class Point {

public:

Point() : x(0), y(0) {

cout<<"Default Constructor called."<<endl;

}

Point(int x, int y) : x(x), y(y) {

cout<< "Constructor called."<<endl;

}

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

int getX() const { return x; }

int getY() const { return y; }

void move(int newX, int newY) {

x = newX;

y = newY;

}

private:

int x, y;

};

int main() {
cout << "Step one: " << endl;
Point *ptr1 = new Point; //调用默认构造函数
cout<<ptr1->getX()<<endl; //输出GetX
delete ptr1; //删除对象,自动调用析构函数
cout << "Step two: " << endl;
ptr1 = new Point(1,2);
cout<<ptr1->getX()<<endl; //输出GetX
delete ptr1;
return 0;
}

int main()
{
    Point *p;//1、实例化指针对象 
    cout << "Step one: " << endl;
    p=new Point;//2、创建对象,动态分配内存
    cout<<p->getX()<<endl;//3、指针访问成员函数 
    delete p;//4、删除对象,注意不是删除指针,后续还可用指针
    cout << "Step two: " << endl;
    p=new Point(1,2);
    cout<<p->getX()<<endl;
    delete p;
    return 0;
}

Point::Point() 
{
    x=0;
    y=0;
    cout<<"Default Constructor called."<<endl;
}

Point::Point(int a,int b)//构造函数重载 
{
    x=a;
    y=b;
    cout<< "Constructor called."<<endl;
}

int Point::getX() const//const禁止修改 
{
    return x; 
} 

int Point::getY() const//const禁止修改 
{
    return y; 
} 

void Point::move(int newX, int newY)//功能类似set()函数 
{
    x=newX;
    y=newY;
}

Point::~Point()
{
    cout<<"Destructor called."<<endl; 
}
//StudybarCommentBegin
#include <iostream>
using namespace std;
class Point {
public:
	Point();
	Point(int x, int y);
	~Point();
	int getX() const; 
	int getY() const; 
	void move(int newX, int newY);
private:
	int x, y;
};
//StudybarCommentEnd

-END

posted @ 2023-04-22 22:00  找回那所有、  阅读(61)  评论(0)    收藏  举报
这里到底了哦~(●'◡'●)