12.17 Nested types in classes

주홍영·2022년 3월 17일
0

Learncpp.com

목록 보기
141/199

https://www.learncpp.com/cpp-tutorial/nested-types-in-classes/

아래에 코드를 보자

#include <iostream>

enum class FruitType
{
	apple,
	banana,
	cherry
};

class Fruit
{
private:
	FruitType m_type {};
	int m_percentageEaten { 0 };

public:


	Fruit(FruitType type) :
		m_type { type }
	{
	}

	FruitType getType() const { return m_type;  }
	int getPercentageEaten() const { return m_percentageEaten;  }
};

int main()
{
	Fruit apple { FruitType::apple };

	if (apple.getType() == FruitType::apple)
		std::cout << "I am an apple";
	else
		std::cout << "I am not an apple";

	return 0;
}

위의 코드는 문제가 없다
하지만 Fruit 클래스를 위해 사용되는 enum 타입이 독립적으로 존재한다는 것은 약간 이상하다

Nesting types

function과 data가 클래스의 member인 것 처럼
c++에서는 타입들도 클래스 내부에서 정의될 수 있다
위의 예시를 아래와 같이 바꿀 수 있다

#include <iostream>

class Fruit
{
public:
	// Note: we've moved FruitType inside the class, under the public access specifier
	enum FruitType
	{
		apple,
		banana,
		cherry
	};

private:
	FruitType m_type {};
	int m_percentageEaten { 0 };

public:


	Fruit(FruitType type) :
		m_type { type }
	{
	}

	FruitType getType() const { return m_type;  }
	int getPercentageEaten() const { return m_percentageEaten;  }
};

int main()
{
	// Note: we access the FruitType via Fruit now
	Fruit apple { Fruit::apple };

	if (apple.getType() == Fruit::apple)
		std::cout << "I am an apple";
	else
		std::cout << "I am not an apple";

	return 0;
}

물론 다른 타입들도 nested 될 수 있다

자세한 내용은 링크를 통해 확인할 것

profile
청룡동거주민

0개의 댓글