본문 바로가기

[C,C++]

[C,C++ 개념정리] 객체지향의 시작

728x90

 < 객체지향언어의 시작 >

 

  객체지향언어는 굉장히 익숙한 개념이지만, 이왕 C++을 정리하기로 했으니 기본적인 내용도 포스팅하기로 했다. 방법 1~5로 이르기까지 객체지향언어를 왜 사용하는지 알 수 있는 코드들이다. 목적은 친구의 정보를 출력하는 것인데 타이핑을 간결하게 해서 실수를 줄이고, 반복하는 상황에서 편이를 추구하기위해 코드가 발전하는 모습을 코드에 나타내었다. 사실, 너무 기본적이라 안봐도 무관한 내용이다;;;

- 코드 - 

/*
    <2020.03.19>

    [8.1강 객체지향 프로그래밍과 클래스]

    매개변수가 정해지지 않았으면 좋겠다... 할때 생략부호를 사용한다.


*/

#include <iostream>
#include <string>
#include <vector>

using namespace std;

// 방법 5. c++ class 사용할 때
class Friend
{
public: // access specifier
    string name;
    string address;
    int age;
    double height;
    double weight;

    // 멤버 뱐수로 집어넣는다.
    void print(){
        cout << name << " " << address << " " << age << " " << height << " " << weight << endl; 
    }
};

// 방법 5. c++ stuct 사용할 때
// struct Friend{
//     string name;
//     string address;
//     int age;
//     double height;
//     double weight;

//     // 멤버 뱐수로 집어넣는다.
//     void print(){
//         cout << name << " " << address << " " << age << " " << height << " " << weight << endl; 
//     }
// };

// 방법 1~4일때
// struct Friend{
//     string name;
//     string address;
//     int age;
//     double height;
//     double weight;
// };

// void print(const string &name, const string &address, const int &age,
// const double &height, const double &weight){
//     cout << name << " " << address << " " << age << " " << height << " " << weight << endl; 
// }

// void print(const Friend &fr){
//     cout << fr.name << " " << fr.address << " " << fr.age << " " << fr.height << " " << fr.weight << endl; 
// }

int main()
{
    // 방법 1.
    // string name;
    // string address;
    // int age;
    // double height;
    // double weight;

    // print(name, address, age, height, weight);

    // 방법 2.
    // vector<string> name_vec;
    // vector<string> addr_vec;
    // vector<int> age_vec;
    // vector<double> height_vec;
    // vector<double> weight_vec;

    // print(name_vec[0], addr_vec[0], age_vec[0], height_vec[0], weight_vec[0]);

    // 방법 3.
    // Friend jj{"jack","busan",2,1.0,1.0}; // uniform initialization
    // print(jj.name, jj.address, jj.age, jj.height, jj.weight);

    // 방법 4.
    // Friend jj{"jack","busan",2,1.0,1.0};
    // print(jj);

    // 빙법 5.
    Friend jj{"jack","busan",2,1.0,1.0}; // instanciation, instance
    // cout << &jj << endl;
    jj.print();

    // 사람이 많아진다면...
    vector<Friend> my_friends;
    my_friends.resize(2); // 친구 2명분의 공간이 생긴다.

    // my_friends[0].print();
    // my_friends[1].print();
    //  ... 친구가 1000명이라면?

    // 많으면 for문 돌리면 된다.
    for(auto &ele : my_friends)
        ele.print();

    // 멤버변수에는 m_으로 시작하도록 만들기도 한다.(멤버변수임을 알기 쉽게 하기 위해서)

    return 0;
}

 

 - 출력 결과 -

728x90