2016-10-14 2 views
1

프로그램의 목적은 라우드 스피커 인클로저의 시뮬레이션 스크립트를 생성하는 것이 었습니다.상위 데이터 멤버 값을 하위 클래스로 전달

따라서 나는 스피커를 정의하는 클래스 스피커를 가지고 있습니다.

모든 인클로저의 공통 매개 변수를 포함하는 상위 클래스 인클로저.

자신의 스페셜 속성이있는 하위 클래스입니다. 다형성과 상속을 사용

나는 완벽하게 잘 작동 첫 번째 프로그램을 얻을하지만 난 인클로저의 기본 속성마다 다시 계산해야합니다 내 프로그램의 경우

class speaker 
{  
} 
class Enclosure 
{ 
     int m_boxHeight; 
     speaker * m_speakerBass;//... 
     public://some functions 
} 
class closedBox : public Enclosure 
{   
    public: 
     closedbox(speaker &speakerbass):Enclosure(speakerbass)// some functions    
    protected: 
     int paramclosed1;//...    
} 

int main() 
{  
    speaker speakerbass; 

    cout <<endl<< "Please choose in the available enclosure proposals" << endl; 
    cout << "1 Closed box enclosure" << endl; 
    // cout << "2 Bass reflex enclosure" << endl; 
    // cout << "3 and so on..." << endl; 
    int choice; 
    cin>>choice; 
      switch (choice) 
     { 
     case 1: 
      closedbox * ClBox2Simu; 
      ClBox2Simu= new closedbox(speakerbass);  
      delete ClBox2Simu; 
      break; 
     case 2: 
      //... same but with bassreflex class child  
      break; 

     default: 
      cout<<"Then good bye"; 

     } 
    return 0; 
} 

를 부모 클래스의 멤버 데이터 수 아이에게 줄 수 있습니다. 즉, Enclosure의 상자 크기는 각 하위 클래스 bassreflex 또는 closedbox에서 동일합니다.

  • 을 상위 클래스를 만들

  • 부모 매개 변수를 사용하여 아이를 작성 최초의 초기 일반적인 계산 (문제를) 수행

    따라서 나는 방법에 대한이 지금 할 경우

기본적으로 child = 금지 된 parent. 이 코드의 아이디어에서 :

class speaker 
{ 
    public:  // some functions 
    protected: 
     int fs; 
     int paramSpeaker2;   //...  
} 
class Enclosure 
{  
    public:   //some common function 
    protected: 
     int m_boxHeight; 
     speaker *m_speakerBass //...  
} 
class closedBox : public Enclosure 
{  
    public: 
     closedbox(); // some functions 
    protected: 
     int paramclosed1; //...  
} 
class bassreflex : public Enclosure 
{  
    public: 
     bassreflex(); // some functions 
    protected: 
     int paramclosed1; //...  
} 

int main() 
{  
    Enclosure initialBox;// calculate dimension,choose speaker... 

      closedbox * ClBox2Simu; 
      ClBox2Simu= initialBox;// child= parent which is forbidden 
      //do stuff concerning closedbox 
      delete ClBox2Simu; 

      bassreflex * BassReflex2Simu; 
      BassReflex2Simu= initialBox; //forbidden 
      //do stuff concerning bassreflex 
      delete BassReflex2Simu; 

      //... and so on for other child class using enclosure 

     delete initialBox 
    return 0; 
} 

는 분명 희망! 만약 설명

+2

왜 직접 하위 클래스를 초기화하지 않습니까? 읽는 시간 [생성자 및 멤버 초기화 목록] (http://en.cppreference.com/w/cpp/language/initializer_list) – Danh

+0

"기본 속성 재 계산"의 위치 (또는 이유)를 이해하지 못합니까? – UnholySheep

+0

첫 번째 예제의 동적 할당은 완전히 필요하지 않습니다. – molbdnilo

답변

1

증상은 통상적 인 -A 대 갖는다-A, 즉 유전 대 조성물 문제 제시한다.

C++에서 원칙은 하위 개체를 만드는 것입니다. 아이의 제작 과정은 다음

  • 제 동봉 부모 오브젝트는 자식 멤버
  • 를 제작하고 마지막 하위 생성자 체의 구성을 완성하기 위해 실행되는 다음
  • 가 구성된다.

이 논리에 문제가 발생하는 즉시 상속이 최선의 방법이 아님을 제안합니다. OOP의 통상적 인 조언은 이상의 합성을 선호하는 입니다. 원칙적으로 상속은 객체의 본질이 변경되지 않는 경우에만 사용되어야합니다.

귀하의 경우에는
class animal {}; 
class cat : public animal {}; // ok: a cat will always remain an animal 

class person {}; 
class employee : public person {}; // bad idea: a person could have several job 
            // or change job or (hopefully temporarily) without job 

// possible alternative 
class job_t { string title, company; date from,to; ... }; 
class person { vector<job_t> jobs; ... }; // very flexible 

, 나는 Enclosure은 몇 가지 일반적인 매개 변수가 있음을 이해하고 싶지만, 형상 계수가 : 여기 도메인, 전형적인 더 친숙한 예에 익숙하지 않아요으로

(나는이 가족이라고 부름)이 파도가 환경과 다른 기능에 어떻게 전달되는지를 결정합니다.

class EnclosureFamily { 
    public: 
     double compute_volume_in_room() = 0; // abstract; 
}; 
class Enclosure 
{  
    public:   //some common function 
     double compute_volume_in_room() { 
      return f->compute_volume_in_room(); // forwarding 
     } 
    protected: 
     int m_boxHeight; 
     speaker *m_speakerBass; 
     EnclosureFamily *f; // ok, but smart ponters should be preferred 
}; 
class BoxEnclosure : public EnclosureFamily { 
    public: 
     double compute_volume_in_room() { ... }; 
}; 

이 원하는대로 인클로저 가족을 변경할 수 있습니다 :

는이 경우에 갈 수 있습니다. 그건 그렇고, 이것은 strategy pattern의 구현입니다. 내가 그 길을가는 조언을하지 않을 그러나

*static_cast<Enclosure*>(BassReflex2Simu)= initialBox; // not forbidden but slicing 

(의 유지 : 당신이 정말로 당신의 원래 디자인을 유지해야하는 경우

, 당신은 부모에게 캐스팅 슬라이스 효과를 활용하여 부모 클래스를 덮어 쓸 수 있습니다 먼저 부모에게 3의 규칙을 올바르게 구현해야한다는 것을 염두에 두십시오.

+0

그래, 가능하지만 다용도는 아니지만, 각 하위 클래스에 일반 매개 변수에 대한 포인터를 추가해야합니다. 따라서 어느 날 부모에게 일반 매개 변수를 추가하면 수동으로 모든 하위 클래스를 업데이트해야합니다. 고맙습니다 ! – Boulgour

관련 문제