반응형

배열 동적할당

#include <iostream>

using namespace std;

int main() {
    int *arr;
    int length = 10;

    arr = new int[length];

    for (int i=0; i<length; i++) {
        arr[i] = i;
    }

    for (int i=0; i<length; i++) {
        cout << arr[i] << endl;
    }

    delete[] arr;

    return 0;
}

 

객체 동적할당

#include <iostream>

using namespace std;

class Vector2 {
    private:
        float x;
        float y;
    public:
        Vector2() : x(0), y(0) {

        }

        Vector2(float x, float y) : x(x), y(y) {

        }

        float getX() {
            return x;
        }

        float getY() {
            return y;
        }
};

int main() {
    Vector2 v1 = Vector2();
    Vector2 v2(3, 2);

    Vector2 *v3 = new Vector2();
    Vector2 *v4 = new Vector2(3, 2);

    cout << v1.getX() << ", " << v1.getY() << endl;
    cout << v2.getX() << ", " << v2.getY() << endl;
    cout << v3->getX() << ", " << v3->getY() << endl;
    cout << v4->getX() << ", " << v4->getY() << endl;

    delete v3;
    delete v4;

    return 0;
}
반응형

'Development > C, C++' 카테고리의 다른 글

[C++] 클래스  (0) 2019.04.04
[C++] 문법  (0) 2019.04.04
[C] 유용한 함수들  (0) 2019.04.04
[C] 파일 입출력  (0) 2019.04.04
[C] 상수  (0) 2019.04.04

+ Recent posts