2013-05-15 3 views
1

그래서 클래스를 불렀다 사람전화 확장 한 클래스 기능

class Person{ 

    private: 

    public: 
     Person(); 

} 

1 개 클래스 환자 내가

을 추천했습니다의 배열을 만들었습니다 지금

class Patient : public Person{ 

    private: 
     string text_; 
    public: 
     Patient(); 
     void setSomething(string text){ text_ = text; } 
} 

Person *ppl[5]; 

및 5 명의 환자

ppl[0] = new Patient(); 
ppl[1] = new Patient(); 
ppl[2] = new Patient(); 
ppl[3] = new Patient(); 
ppl[4] = new Patient(); 

같은 배열의 각 키에 지금은이

ppl[0]->setSomething("test text"); 

처럼 환자 클래스에서 setSomething에게 기능 를 호출 할 그러나 나는 다음과 같은 오류가 계속 :

class Person has no member named setSomething 
+0

무엇이 문제입니까? 컴파일러는 무엇이 잘못되었는지에 대해 매우 분명합니다. 'Person'은'setSomething' 메쏘드가 없으므로'Person'이나'Person'에 대한 포인터로 호출 할 수 없습니다. – juanchopanza

+0

나는 Patient가 Person을 확장한다고 덧붙여서 배열의 모든 요소가 Patient 클래스에서 함수를 호출 할 수 있기 때문에 – fxuser

+0

이 가능하다고 생각했습니다. – fxuser

답변

2

배열의 배열은 Person*입니다. Patient 개체를 가리키는 경우에도 배열의 요소에서 Person의 public 메서드 만 호출 할 수 있습니다. Patient 메소드를 호출하려면 먼저 Person*Patient*으로 전송해야합니다.

static_cast<Patient*>(ppl[0])->setSomething(...); 

어느 쪽이든, 또는 setSomethingvirtual 기능을합니다

Person* person = new Patient; 
person->setSomething("foo"); // ERROR! 

Patient* patient = dynamic_cast<Patient*>(person); 
if (patient) 
{ 
    patient->setSomething("foo"); 
} else 
{ 
    // Failed to cast. Pointee must not be a Patient 
} 
1

컴파일러는 당신이 가지고 Patient 객체에 대한 포인터 점, 그래서 명시 적으로는 컴파일러에게 것을 알고하지 않습니다 기본 클래스에서.

작은 노트 : static_cast을 사용하면 포인터가 Patient 개체에 대한 포인터라는 것이 확실한 경우에만 작동합니다. 변경 사항이 없다면 dynamic_cast을 대신 사용하고 결과가 nullptr이 아닌지 확인해야합니다.