가끔씩 프로퍼티 & 기본 클래스 포인터의 벡터에 저장되어있는 서브 클래스의 메소드에 액세스해야하기 때문에 프로그램에 디자인 문제가 있습니다. 그것은 보인다 경우서브 클래스의 프로퍼티/함수에 액세스하기 C++
가void Thing::doB1Stuff() {
for(std::vector<Base*>::iterator it = bases.begin(); it != bases.end(); ++it) {
if (it->getB1()) {
//do stuff with b1
}
}
}
은 위의 코드는 작동해야하지만 :이 아래처럼 살아라에서 X 또는 Y에 액세스해야하는 경우
class B1;
class B2;
class Base {
private:
int id, a, b;
public:
virtual int getA() { return a; }
virtual int getB() { return b; }
virtual B1 *getB1() { return NULL; } //seems like a bad idea
virtual B2 *getB2() { return NULL; } //to have these two functions
Base(int newId) { id = newId; }
};
class B1 : public Base {
private:
int x;
public:
int getX() { return x; }
B1 *getB1() { return this; }
};
class B2 : public Base {
private:
int y;
public:
int getY() { return y; }
B2 *getB2() { return this; }
};
class Thing {
private:
std::vector<Base*> bases;
void addBase(Base *base) { bases.push_back(base); }
void doB1Stuff();
void doB2Stuff();
void setAandB(int ID, int newA, int newB); //set a and b of one of the elements in bases vector based upon the id given
};
문제는 : 내 코드는 다음과 같이 보입니다 하나는 쉽게 다음과 같이 B1/B2 속성을 사용하기 전에 포인터가 null의 경우 확인하는 것을 잊지 수 있기 때문에 나쁜 생각 :
따라서void Thing::doB2Stuff() {
for(std::vector<Base*>::iterator it = bases.begin(); it != bases.end(); ++it) {
std::cout << it->getY(); //I believe this will crash the program if a NULL pointer is returned
}
}
내 질문은 : 서브 클래스의 속성에 액세스하는 좋은 방법은 무엇입니까? 내가 B1과 B2를위한 두 개의 별개의 벡터를 가지고 있다고 생각하고 있었지만 a와 b를 쉽게 설정할 수 있어야하기 때문에 좋지 않은 것 같습니다. 이견있는 사람?
클래스가 해당 상황에서 근본적으로 다르게 동작하는 경우 배열에서 클래스를 혼합해서는 안됩니다. 대신에 템플릿을 사용하고 싶습니까? – Dave
정확한 문제는'dynamic_cast'로 해결됩니다. (또는 더 나은 디자인) –