1 minute read

07-1 [상속과 생성자의 호출]

  • 코드💻
/*
 * 두 클래스에 적절한 생성자와 소멸자를 정의해보자
 * 그리고 확인을 위한 main함수를 정의해보자
 */
#define _CRT_SECURE_NO_WARNINGS

#include<iostream>
using namespace std;

class MyFriendInfo {
private:
	char* m_pName;
	int m_Age;

public:
	MyFriendInfo(const char* name, int age);
	~MyFriendInfo();
	void ShowMyFriendInfo() {
		cout << "이름 : " << m_pName << endl;
		cout << "나이 : " << m_Age << endl;
	}
};

MyFriendInfo::MyFriendInfo(const char* name, int age) {
	m_pName = new char[strlen(name) + 1];
	strcpy(m_pName, name);
	m_Age = age;
	cout << "constructor" << endl;
}

MyFriendInfo::~MyFriendInfo() {
	delete[]m_pName;
	cout << "destructor" << endl;
}


class MyFriendDetailInfo : public MyFriendInfo {
private:
	char* m_pAddr;
	char* m_pPhone;

public:
	MyFriendDetailInfo(const char* name, int age, const char* addr, const char* phone) 
		: MyFriendInfo(name, age) {
		m_pAddr = new char[strlen(addr) + 1];
		m_pPhone = new char[strlen(phone) + 1];

		strcpy(m_pAddr, addr);
		strcpy(m_pPhone, phone);
		
		cout << "derived constructor" << endl;
	};

	~MyFriendDetailInfo() {
		delete[]m_pAddr;
		delete[]m_pPhone;
		cout << "derived destructor" << endl;
	};

	void ShowMyFriendDetailInfo() {
		ShowMyFriendInfo();
		cout << "주소 : " << m_pAddr << endl;
		cout << "번호 : " << m_pPhone << endl;

	}
};

int main(void) {
	MyFriendInfo choi("choi", 21);
	choi.ShowMyFriendInfo();

	MyFriendDetailInfo sohn("sohn", 22, "경기", "1243");
	sohn.ShowMyFriendDetailInfo();

	MyFriendDetailInfo lee = sohn;
	lee.ShowMyFriendDetailInfo();

	return 0;
}


  • Heap Corruption detected라고 에러가 나는데, 이유는 new char[]로 메모리를 할당해놓고 문자열을 연결하거나 메모리가 달라진 후 delete하려하기 때문이라고 한다. 근데 왜 저번날의 코드는 멀쩡했을까요.

07-2-1 [IS-A 관계의 상속]

  • 코드💻
/* 문제1
 * 정사각형 클래스와 직사각형 클래스를 정의하고자한다
 * 정사각형은 직사각형 일종이므로 상속관계를 구성한다.
*/

#include<iostream>
using namespace std;

class Rectangle
{
public:
	Rectangle(int width, int height);
	~Rectangle();

private:
	int m_Width;
	int m_Height;

public:
	void ShowAreaInfo();
};

Rectangle::Rectangle(int width, int height) : m_Height(height), m_Width(width)
{
}

Rectangle::~Rectangle()
{
}

void Rectangle::ShowAreaInfo()
{
	cout << "area: " << m_Height * m_Width << endl;
}



class Square : public Rectangle
{
public:
	Square(int len);
	~Square();

private:
	int m_Len;      // 한변의 길이

};

Square::Square(int len) : Rectangle(len, len)
{
}

Square::~Square()
{
}

int main(void) {
	Rectangle rec(4, 3);
	rec.ShowAreaInfo();

	Square sqr(7);
	sqr.ShowAreaInfo();
	return 0;
}
  • 유도클래스에 굳이 기능을 더 추가해서 풍부하게 만들지 않아도 된다는 생각을 할 수 있게끔 하는 문제였는데, 유도클래스가 너무 휑해보인다

Tags: ,

Categories:

Updated: