본문 바로가기
Languages/C++

구조체와 클래스

by 반도체는 프로그래밍을 좋아해 2022. 12. 17.
728x90

C++ 에서의 구조체

# 첫번째 방법
typedef struct sTag {
	char m;
} sType;

# 두번째 방법 태그명을 바로 타입으로 인정
# 태그명을 생략할 시 1회성 구조체가 된다.
struct sTag {
	char m;
}

 

C++에서의 객체는 상태와 행위를 가진다.

상태란? ex) 이름, 색상 등등 // 행위는? ex) 행동

이를 코드로 작성하면 상태는 구조체, 행위는 함수로 나타난다.

 

예시

# Complex.h

#pragma once
#include <cstdio>

class Complex
{
	# 상태
	double real;
 	double imag; 
 public:
 	# 행위
 	void set ( double r, double i ){
    	real = r;
        imag = i;
    }
    void read ( char* msg = "복소수 = ") {
    	printf(" %s ", msg);
        scanf("%1f%1f",&real, &imag);
    }
    # ...
Class Member Data General Member Data
Static Member Data
Member Function -> Static에 가까움

위 얘시에서 상태는 Member Data이고 General에 가깝다 Static의 경우 각 클래스 객체에서 공유하는 개념

행위는 function이다.

 

배열 + 클래스를 이용한 다항식 클래스 만들기

# Polynomial.cpp

# "" > <> 이다 컴파일의 범위 차이
# include "Polynomial.h" 

void main() {
	Polynomial a, b, c;
    a.read(); // 다항식 a 읽기(직접 입력)
    b.read(); // 다항식 b 읽기(직접 입력)
    c.add (a, b);
    a.display("A = ");
    b.display("B = ");
    c.display("A + B = ");
}
# Polynomial.h

#define MAX_DEGREE 80  //다항식 배열의 최대 크기 +1
# include <cstdio>

class Polynomial {
	int degree; // 다항식 최고차수
    float coef[MAX_DEGREE]; // 각 항의 계수
public:
	Polynomial() { degree = 0; } // 생성자
    void read() {
    	printf(" 다항식의 최고 차수를 입력하시오: ");
        scanf("%d", &degree);
        printf("각 항의 계수를 입력하시오 ( 총 %d개): ", degree +1);
        for(int i =0 ; i <degree ; i++){
        	scanf("%f", coef+i); }
     }
	void display(char *str = " Poly = ") {
    	printf("\t%s", str);
        for(int i = 0; i < degree; i++){
        	printf("%5.1f x^%d + ", coef[i], degree-i);}
        printf("%4.1f\n", coef[degree]);
    }
    void add( Polynomial a, Polynomial b) {
    	if(a.degree > b.degree) {
        	*this = a;
            for(int i = 0; i<=b.degree ; i++){
            	coef[i+(degree-b.degree)] += b.coef[i];}
        }
        else {
        	*this = b;
            for(int i = 0; i<=a.degree ; i++){
            	coef[i+(degree-a.degree)] += a.coef[i];}
        }
    }
    bool isZero() { return degree == 0; }
};

 

728x90

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

자료구조 - 트리  (0) 2022.12.18
자료구조 - 리스트  (0) 2022.12.18
포인터와 연결리스트  (0) 2022.12.18
자료구조-큐  (0) 2022.12.17
자료구조 - 스택  (0) 2022.12.17