C++类型数组的构造与析构

#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<< "Parameter 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() {
    Point *ptr = new Point[5];
    ptr[0].move(5, 10);    
    ptr[1].move(15, 20);
    cout << "Deleting..." << endl;
    delete[] ptr;
    return 0;
}
#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<< "Parameter 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;
    delete ptr1;
    cout << "Step two: " << endl;
    ptr1 = new Point(1,2);    
    delete ptr1;

    return 0;
}

原文链接: https://www.cnblogs.com/lyt888/p/12493331.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/194320

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月12日 下午6:39
下一篇 2023年2月12日 下午6:39

相关推荐