码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2020-03-14 18:15:38      阅读:53      评论:0      收藏:0      [点我收藏+]

标签:ret   code   类型   pre   style   ace   let   str   cal   

#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;
}

 

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

标签:ret   code   类型   pre   style   ace   let   str   cal   

原文地址:https://www.cnblogs.com/lyt888/p/12493331.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!