나는 C++을 배우고 있으며 문제가 있습니다. 기본 클래스 내에서 특정 하위 클래스를 사용하는 방법이 필요합니다. 그것은 의미가 있습니까 또는 잘못된 접근 방식을 사용하고 있습니까? SelectBrand가 하위 클래스를 선택해야합니다. 어떻게해야합니까? 여기 내 간단 클래스 아래기본 클래스에서 하위 클래스를 선택할 수 있습니까?
:
-----
class Protocol {
public:
Protocol() {};
~Protocol() {};
int openPort();
int readPort(char *buffer);
.....
private:
Protocol (const Protocol&);
};
int Protocol::openPort() {......};
int Protocol::readPort() {.........};
/***********************************************************************************/
class Device{
public:
Device(Protocol& port):_protocol(port){}
~Device();
virtual int getEvent(char *buffer) { return -1; }
int Device::selectBrand();
..............
protected:
Protocol& _protocol;
private:
int brand;
Device(const Device&orig);
};
Device::~Device() {}
int Device::selectBrand() {
......
switch (X)
case 1:
"use subclass Brand_B"
case 2:
"use subclass Brand_B"
.......
}
/***********************************************************************************/
class Brand_A:public Device {
public:
Brand_A(Protocol& port);
~Brand_A();
int getEvent(void *rawData);
private:
Brand_A(const Brand_A&);
};
Brand_A::Brand_A(Protocol& port):Device(port) {}
Brand_A::~Brand_A() {}
int Brand_A::getEvent(void *rawData) {
.... readPort(......);
}
/***********************************************************************************/
class Brand_B:public Device {
public:
Brand_B(Protocol& port);
~Brand_B();
int getEvent(void *rawData);
private:
Brand_B(const Brand_B&);
};
Brand_B::Brand_B(Protocol& port):Device(port) {}
Brand_B::~Brand_B() {}
int Brand_B::getEvent(void *rawData) {
.... readPort(......);
}
/* main **********************************************************/
int main(int argc, char **argv) {
Device *mydev;
char *buffer;
..............
mydev->selectBrand();
..........
mydev->getEvent(buffer);
...........
}
예제에서 너무 많은 '....'섹션이 있습니다. 'selectBrand'가 실제로하는 일이 명확하지 않습니다 :'X'는 무엇이고 "use subclass"는 무엇을 의미합니까? – casablanca
"선택"하여 서브 클래스를 "가져 오는"객체를 다운 캐스트하려는 경우, 그렇습니다. 접근 방식에 결함이 있습니다. 많은 코드를 제공하는 것이 혼란 스럽습니다. 핵심 클래스, 메소드 및 사용 방법은 어떨까요? – belwood
'~ Device()'는 아마도'virtual'이어야합니다. – fredoverflow