2016-05-31 2 views
0

에서 부울을 반환 기본 클래스에서 함수를 호출 할 수 있습니다 설정된 프로파일은 기본 클래스의 set_profile을 실행하고 다른 작업도 수행합니다.나는 나는 다음과 같은 기본 클래스 한 파생 클래스

방금 ​​이렇게 작성할 수 있습니까?

bool node_layer_manager_with_rad_t::set_profile(void) 
{ 
    bool success; 
    node_layer_manager_t::set_profile(); 
    try 
    { 
     string_t profile_tag = "logs/trx_dump/node:"+get_id(); 
     dev_tx = profile->get_decendant(profile_tag.c_str()); 
     cout<<"sarit id= "<< get_id()<<endl; 
     success = true; 
    } 
    catch(...) 
    { 
     cout<<"sarit profile error: "<<endl; 
     success = false; 
    } 
    return success; //** 
} 

이 ** 또는 내가 follwing을 reurn해야합니다 (그래서 실제로, 이것은 mcve 아닌 처음에는

return (success && node_layer_manager_t::set_profile()); 
+0

이 C에 대한 질문입니다 ++ 또는 약 너의 특별한 디자인? 전자의 경우 언어 규칙을 위반하지 않는 프로그램 만 작성해야합니다. 이 두 가지 변종 모두 OK입니다. 후자의 경우 디자인을 완전히 이해하지 않고는 아무도 아이디어를 얻을 수 없습니다. 잠정적으로 두 번째 변종이 더 유망 해 보인다 (세터 내부의 인쇄는 의심스러워 보인다). –

답변

0

, 어디서든 성공을 선언하지 않은 코드는 컴파일되지해야)입니다.

당신이 첫 번째 또는 하위 클래스의 코드 뒤에 슈퍼 클래스를 호출시겠습니까 ... 당신이 실제로 수행하려는 작업에 따라 달라집니다 및 t 대답은 -

아직도 나는 그것을 얻을? 귀하의 예는 귀하의 대안 인 후자를 의미합니다. 수퍼 클래스 함수가 ​​실패하거나 여전히 코드를 실행하는 경우 중단 하시겠습니까?

귀하의 inital 예제는 수퍼 클래스 함수를 호출하고, 결과를 무시하고 나중에 자체 함수를 수행합니다.

이 먼저 슈퍼 클래스 함수를 호출 만 성공을 계속 : 이것은 모두를 실행

bool success = node_layer_manager_t::set_profile(); 
if(success) 
{ 
    try { /*...*/ } // <- no need to set success to true, it is already 
    catch(...) { /*...*/ success = false; } 
} 

,하지만 결과 결합 : 첫째, 서브 클래스 코드를 실행에

bool success = node_layer_manager_t::set_profile(); 
try { /*...*/ } // <- do not modify success, must remain false if super class failed! 
catch(...) { /*...*/ success = false; } 

귀하의 대안 힌트를 아무 것도 잘못되지 않으면 슈퍼 클래스 함수 만 호출합니다.

이러한 방법 중 하나라도 적절할 수 있으며 그 중 어느 것도 적합하지 않을 수 있습니다. 당신은 당신의 요구 사항이 무엇인지에 대한 명확한 이미지를 얻을 수 있습니다 - 당신이 호출 부모 set_profile에있는 경우 다음 요구 사항을 만족하도록 코드를 구현 ...

+0

두 개의 클래스 중에서 set_profile을 모두 재정의하여 올바르게 선언해도 괜찮습니까? –

+0

[here] (http://en.cppreference.com/w/cpp/language/override)를보십시오 : 네, 괜찮습니다 ('layer_manager_t'도 그러한 가상 함수를 가지고 있습니다!). – Aconcagua

1

을 관계없이 파생 클래스에서해야 할 일, 이 제약 조건에주의를 기울이는 디자인을 채택해야합니다.

일반적으로 final으로 기반 클래스 set_porfile을 표시하고 전용 파생 클래스 메소드의 호출 내부를 기반으로 클래스를 관리해야한다 : 디자인의이 종류로

class node_layer_manager_with_rad_t : public node_layer_manager_t 
{ 
protected: 
    .... 

public: 

    virtual bool set_profile_child() override; 
}; 

// Manage only there own action, regardless of needs of based class 
bool node_layer_manager_with_rad_t::set_profile(void) 
{ 
    try 
    { 
     // Do what you're in charge, and only what you're in charge! 
    } 
    catch(...) 
    { 
     cout<<"sarit profile error: "<<endl; 
     success = false; 
    } 
    return success; //** 
} 

:

class node_layer_manager_t : public layer_manager_t 
{ 
protected: 
    .... 
    // set_profile actions of derived class 
    // proposed a default without side effect implementation if 
    // derived class doesn't need to overload this. 
    virtual bool set_profile_child() { return true; }; 
private: 
    .... 
public: 
    ..... 
    // Manage here call of derived 
    virtual bool set_profile() override final 
    { 
     // actions before derived specific actions 
     .... 
     // Call specific derived class actions 
     bool success = set_profile_child(); 

     // actions after derived specific actions 
     if (success) 
     { 
      //do based class action 
     } 
     return success; 
    } 
} 

와 자식을 , 각 클래스는 오직 관리해야하는 것만 수행하고, 그것만 관리합니다. 파생 클래스는 기반 클래스의 요구를 처리 할 필요가 없습니다.

당신이 코드가 이전 또는 일반 동작 후에 실행되는 경우 결정하기 위해 파생 클래스의 능력을 제공 할 경우, 교체하거나 set_profile_child() 두 가지 방법으로 추가 할 수 있습니다 bool pre_set_profile()bool post_set_profile()

+0

좋은 접근 방법이지만 (+1) 성배도 마찬가지입니다. 하위 클래스의 코드가 실행될 때 명령을 내리므로'class Sub1 :: do (do {() (doSomething(); 수퍼 :: do(); } 클래스 Sub2 :: do() {Super :: do(); doSomethingDifferent(); }'불가능하다 ... – Aconcagua

+0

@Aconcagua 만약이 행동이 필요하다면'bool pre_set_profile()'과'bool post_set_profile()'에 의해'bool set_profile_child()'를 대체 할 수있다 (또는이 3 가지 방법을 가진다) – Garf365

+0

Hum, it 그 점에 대해 정말로 생각하지 않기 때문에 나쁜 대답 일 수 있습니다. 그러나 마음에 떠오르는 첫 번째 대답은 : 기반 클래스가 파생 클래스가 예외를 관리하도록 허용한다면, 기반 클래스는 올바른 인터페이스를 제공해야합니다.> 가상 무효 handle_set_profile_expection (TheException & e)' – Garf365