[C++] struct

dd_ddong·2022년 7월 11일
0

c++

목록 보기
12/38

struct

struct StructTag { };
;을 잊지 말자

C와 차이점

1. 선언

c 정의
struct Car { ... };
c 선언
struct Car car1 = { ... };

c++ 정의
struct Car { ... };
c++ 선언
Car car1 = { ... };

struct 키워드 없이도 구조체 변수 선언 가능

2. 함수 삽입

c++의 경우 함수삽입이 가능하다.

struct Car {
	char * carName;
    int fuel;
    int curSpeed;
    
    void ShowCarState(){
    	cout<< carName << endl;
        cout<< fuel << endl;
        cout<< curSpeed << endl;
    }
}

struct 안에 정의된 함수는 자동으로 inline화 된다.


구조체 내부에 함수의 선언을 하고 정의는 외부에서 할 수도 있다.

struct Car {
	char * carName;
    int fuel;
    int curSpeed;
    void ShowCarState();
    
}
//Car 구조체의 함수라는 걸 명시해줘야한다.
void Car::ShowCarState(){
    	cout<< carName << endl;
        cout<< fuel << endl;
        cout<< curSpeed << endl;
}

함수의 정의가 구조체 밖에 작성된다면 자동 inline화가 일어나지 않는다.

0개의 댓글