태그 글목록: 자식클래스

[C++ 정리] 상속의 기본형과 형변환 2015-06-23

부모 클래스에서 미리 구현된 내용을 상속받아 자식클래스에서 확장한다. 또한 부모 자식관계의 클래스에서 형변환은 기본적으로 ‘자식에 부모를 담지못한다’, ‘부모에 자식은 담을 수 있다’를 유념한다.

class MyClassParent
{
public:
	MyClassParent();
	MyClassParent(int x, int y)
	{
		this->width = x;
		this->height = y;
	}

protected:
	int width;
	int height;

private:
	// Error - private로 선언시 상속받은 클래스에서 접근할 수 없다.
	//  => protected 에 선언한다.
	//int width;
	//int height;
	
};

// 다음과 같은 형태로 상속 받는다.
class MyClass :public MyClassParent
{
public:
	MyClass();
	int getArea()
	{
		return this->width * this->height;
	}
	int initArea;
};

// 다음과 같은 형태로 부모클래스의 생성자를 호출할 수 있다.
MyClass::MyClass():MyClassParent(100, 20)
{
	this->initArea = this->width * this->height;
}

// - END header

int _tmain(int argc, _TCHAR* argv[])
{
	// 상속의 예
	MyClass initClass;
	cout << initClass.initArea;

	// 1>> 형변환	
	// [Error] 자식클래스에 부모객체는 담지 못한다.
	MyClassParent parentClass1;
	/*MyClass childClass1 = parentClass1;*/
	// [OK] 부모클래스에 자식객체는 담을 수 있다.
	MyClass childClass2;
	MyClassParent parentClass2 = childClass2;
	
	// 2>> 포인터간 형변환
	// [ERROR] 자식클래스의 포인터에 부모객체의 주소는 담지 못한다.
	MyClassParent parentClassPointer1;	
	/*MyClass* childClassPointer1 = &parentClassPointer1;*/
	// [OK] 부모클래스의 포인터에 자식객체의 주소는 담을 수 있다.
	MyClass childClassPointer2;	
	MyClassParent* parentClassPointer2 = &childClassPointer2;
	
	// 레퍼런스간 형변환
	// [ERROR] 자식클래스의 참조값에 부모객체의 주소는 담지 못한다.
	MyClassParent parentClassReference1;
	/*MyClass childClassReference1 = &parentClassReference1;*/
	// [OK] 부모클래스의 참조값에 자식객체의 주소는 담을 수 있다.
	MyClass childClassReference2;
	MyClassParent& parentClassReference1 = childClassReference2;

	return 0;
}
* 자식클래스에서는 부모클래스의 public: & protected: 에만 접근이 가능하다.
* 부모클래스에 자식객체는 담을 수 있다. 반대로는 불가하다.
* 부모클래스의 포인터에 자식객체의 주소는 담을 수 있다. 반대로는 불가하다.
* 부모클래스의 참조값에 자식객체의 주소는 담을 수 있다. 반대로는 불가하다.