#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; }
void move(int newX, int newY) {
x = newX;
y = newY;
}
private:
int x, y;
};
int main() {//主函数
cout << "Step one:" << endl;
Point *ptr1 = new Point;//动态创建对象,没有给出参数列表,因此调用默认构造函数
delete ptr1;//删除对象,自动调用析构函数
cout << "Step two:" << endl;
ptr1 = new Point(1, 2);//动态创建对象,给出参数列表,因此调用有参构造函数
delete ptr1;//删除对象,自动调用析构函数
return 0;
}
38.C++动态创建对象
最新推荐文章于 2022-03-06 20:11:44 发布