📝 상속관계에서 생성자와 소멸자의 실행
📝 생성자의 매개변수 전달
#include <iostream>
#include <string>
using namespace std;
class TV {
int size;
public:
TV() { size = 10; }
TV(int size) { this->size = size; }
int getSize() { return size; }
};
class WideTV : public TV {
bool videoIn;
public:
WideTV(int size, bool videoIn) : TV(size) {
this->videoIn = videoIn;
}
bool getvideioIn() {
return videoIn;
}
};
class SmartTv : public WideTV {
string ipAddr;
public:
SmartTv(string ipAddr, int size) : WideTV(size, true) {
this->ipAddr = ipAddr;
}
string getIpAddr(){ return ipAddr; }
};
int main() {
SmartTv htv("192.0.0.1", 32);
cout << "size=" << htv.getSize() << endl;
cout << "videoIn=" << htv.getvideioIn() << endl;
cout << "IP=" << htv.getIpAddr() << endl;
}
📝 상속 지정
- 상속 지정자
- public - 기본 클래스의 protected, public멤버 속성 그대로 계승
- private - 기본 클래스의 protected, public멤버를 private으로 계승
- protected - 기본 클래스의 protected, public멤버를 protected로 계승
📝 다중 상속
- 여러 클래스를 동시에 상속 받는 방법
- ex) class multimediaPlaer : public mp3, public video
#include <iostream>
#include <string>
using namespace std;
class Adder {
protected:
int add(int a, int b) { return a + b; }
};
class Subtractor {
protected:
int minus(int a, int b) { return a - b; }
};
class Cal : public Adder, public Subtractor {
public:
int calc(char op, int a, int b) {
int res = 0;
switch (op)
{
case '+': res = add(a, b);
break;
case '-': res = minus(a, b);
break;
default:
break;
}
return res;
}
};
int main() {
Cal handCal;
cout << "2 + 4 = " << handCal.calc('+', 2, 4) << endl;
cout << "100 - 8 = " << handCal.calc('-', 100, 8) << endl;
}