c++ 구조체/struct/member data(멤버 데이타)/구조체에 함수 넣기

c++ 구조체


구조체는 객체를 표현하기 위해 하나 이상의 변수가 필요한 프로그래밍을 하기 위해 ㅍ ㅣㄹ요한것이다.

나 를 표현하기 위해서,
나에 대한것, 성별, 키, 몸무게 , 럭키 넘버등등

std::string myName;
int myGender
int myHeight
int myWeight
int myLucky number;

이것들은 그룹화 되지 않은 독립 변수들이다.
이러면 진짜 귀찮아진다.

집계 데이터 유형은 여러 개별 변수를 함께 그룹화 하는 데이터 유형이다
가장 단순한 집계 데이터 유형 중 하나는 구조체다.

구조체는 하나 이상의 독립된 변수를 그룹 지어서 새료운 자료로 정의하는것이다.


#include <iostream>
#include <cmath>

struct Point{

     double x;
     double y;

};

point 라는 구조체는 2개의 변수를 포함한다. ( double x , double y)

이 구조체 안에 들어있는 x 와 y 변수를 멤버(member) 또는 필드(field) 라고 한다

이 구조체는 단지 선언에 불과하다.
지금은 어떤 메모리도 할당되지 않았고
그냥 변수들을 묶은 그룹뿐이다.


그래서 이 Point 라는 구조체를 사용할려면
Point 타입의 변수를 선언하면 된다.

Point korea; //구조체 Point 타입의 변수를 정의한다.... 0> 해당 변수에 대한 메모리가 할당된다.

#include<iostream>
#include<cmath>

Point korea;// creating Point struct for Korea
korea.x = 100;;
korea.y=200;

또는
Point korea = {100, 200}; 이렇게 초기화 해줘도 됌

수동으로 초기화를 해야함.



그런데 주소를 치면

10000
10004

로 된다

메모리상에서는 이 x y 의 데이터는 따닥따닥 부터있는걸 알수있다.



C++ 구조체에 함수 넣기


struct Time{
     int h, m , s;
};

int totlaSec(Time t){
     return 3600*t.h + 60*t.m+t.s;
}

int main(){
     Time t = { 1, 22, 48 };
     std::cout <<totalSec(t) << std::endl;
}

구조체 Time 이랑 함수 totalSec() 은 정말 밀접한 관계를 가지고있다.
그래서 왠만해서는 붙혀놓고싶다'

그래서 우리가 구조체에 함수를 넣는건데,

struct Time{
     int h, m, s;

     int totlaSec(Time t){
          return 3600*t.h + 60*t.m+t.s;
     }
}

그럼 에러가 떴다

그럼 또 modify를 해줘야한다
struct Time{
     int h, m, s;

     int totlaSec(){
          return 3600*h + 60*m+s;
     }
}

차이점은
totalSec() 이라는 함수의 인자값에 Time t를 선언을 안해줘도 되고
t.h 이나 t.m 이나 t.s 을 안해줘도 된다.

그러니까 일반 함수처럼 된다는 뜻이다
구조체의 이름없이. 구조체의 멤버 변수만 해주면 된다.


#include<iostream>

struct Time{
     int h, m, s;

     int totlaSec(){
          return 3600*h + 60*m+s;
     }
}

int main(){
     Time t = { 1, 22, 48};

     std::cout << "t.toalSec());
}


으로 바꿔주면 된다.'



또 다른 예제,

#include <iostream>
#include <stdio.h>


struct Point {
     int x,y;

     void moveRight(){x++;}
     void moveLeft(){x--;}
     void moveUp(){y++;}
     void moveDown(){y--;}

};

int main(){
     Point p = {2,5};

     p.moveDown();
     p.moveRight();

     std::cout << p.x, p.y << std::endl;


}





mastermind 예제에서...


#incldue <iostream>
#include <cstdlib>
#include <ctime>

플레이어 A
struct mm_code_maker{
 
     void init(int i_lenght, int i_num){
          lenght = i_length;
          num = i_num;
     }

     void generate_sequence(){
          for(int i=0; i<length; i++){
               seqeuence.push_back(randn(num));
          }
     }

     void give_feedback(const std::vector<int> & attemp, int& black_hits, int& white_hits){

     }

     std::vector<int> sequence;

     int length;
     int num;
 
};

플레이어 B - 플레이어 A가 assign 한 색깔 코드를 맞추는것
struct mm_solver{

    void init(int i_length, int i_num){
        length = i_length;
        num = i_num;
     
    }
 
    void create_attempt(std::vector<int>& attempt){
    }
 
    void learn(std::vector<int>& attempt, int black_hits, int white_hits){
    }
 
    int length;
    int num;

};


mm_code_maker 라는 구조체 안에 멤버 함수들이 생성이 되어있다.

멤버 함수들은
void init(int i_lenght, int i_num), 
void generate_sequence() ,
void give_feedback이다.

멤버 변수들은
std::vector<int> sequence;
int length;
int num;
이다




댓글

이 블로그의 인기 게시물

c++ 랜덤 숫자 생성하기 / 컴퓨터 난수 시드 설정

(오라클) View(뷰) + where/order by/like/is/() / in 사용방법 예제

(오라클) Sequence/시퀸스의 활용과 개념