9.13 Introduction to program-defined (user-defined) types

주홍영·2022년 3월 14일
0

Learncpp.com

목록 보기
104/199

https://www.learncpp.com/cpp-tutorial/introduction-to-program-defined-user-defined-types/

What are user-defined / program-defined types?

c++은 programmer가 custom으로 만들어 사용할 수 있는 타입을 지원한다
이러한 타입을 user-defined types (program-defined types)라고 한다
이러한 타입에는

  • enumerated types (unscoped and scoped enumerations)
  • class types (including structs, classes, and unions)
    등 이 있다

Defining program-defined types

아직 struct에 대해서 다루지 않았지만 struct type을 정의하고 instantiate하는 방법은
다음 코드를 사려보면 알 수 있다

// Define a program-defined type named Fraction so the compiler understands what a Fraction is
// (we'll explain what a struct is and how to use them later in this chapter)
// This only defines what a Fraction type looks like, it doesn't create one
struct Fraction
{
	int numerator {};
	int denominator {};
};

// Now we can make use of our Fraction type
int main()
{
	Fraction f{ 3, 4 }; // this actually instantiates a Fraction object named f

	return 0;
}

Type definitions are exempt from the one-definition rule

우리는 function을 define할 때 header file에 forward declaration을 하고
코드 파일에 함수를 정의함으로써 one-definition rule을 만족 시켰다

만약 type definition에서도 동일한 규칙이 적용되면 우리는 오직 forward dec로만 전파할 수 있다는 것이다
하지만 type defintion에서는 이는 충분치 않다

결론적으로 type은 앞서말한 one-def rule에서 면제다
따라서 full type def는 복수의 파일에 propagate가 가능하다
그게 duplicate def일 지라도

이때 동일한 type에 대한 definition은 모두 동일해야 한다

profile
청룡동거주민

0개의 댓글