Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > C/C++: Общие вопросы > Почему ловиться исключение с типом A, а не с B ?


Автор: Alca 10.1.2013, 00:19
Код

#include <iostream>
    
 class A {
     public:
        A()                { std::cout << "A::A()\n"; }
        virtual void Foo() { std::cout << "A::Foo()\n"; }
 };

 class B : 
     public A
 {
     public:
         B()                { std::cout << "B::B()\n"; }
         virtual void Foo() { std::cout << "B::Foo()\n"; }
 };

 int main() {
     try {
         throw B();
     }
     catch(A ex) {
         std::cout << "catch(A ex)\n";
         ex.Foo();
     }
     catch(B &ex) {
         std::cout << "catch(B &ex)\n";
         ex.Foo();
     }

     return 0;
 }


Код

Compilation finished with warnings:
source.cpp: In function 'int main()':
source.cpp:25:6: warning: exception of type 'B' will be caught [enabled by default]
source.cpp:21:6: warning:    by earlier handler for 'A' [enabled by default]

            
stdout: 
A::A()
B::B()
catch(A ex)
A::Foo()


http://liveworkspace.org/code/DrAi1$5

Почему ловиться исключение с типом A, а не с B ?

Автор: mes 10.1.2013, 00:24
потому что B приводится к A, а catch с А первый..

Автор: Alca 10.1.2013, 00:26
Не знал, спасибо

Автор: mes 10.1.2013, 00:37
Цитата(Alca @  9.1.2013,  23:19 Найти цитируемый пост)
source.cpp:25:6: warning: exception of type 'B' will be caught [enabled by default]
source.cpp:21:6: warning:    by earlier handler for 'A' [enabled by default]

кстати компилятор сообщил почти на чисто руссском об этом smile

Автор: Alca 10.1.2013, 00:39
Чего то не вчитывался в этот ворнинг, 
с таким приведением никогда не сталкивался

Автор: Alca 14.1.2013, 16:47
А если так:
Код

 //...

 class B : 
     protected /* or private */ A
 {
    // ...
 };

 // ...

то будет ловиться B:
Код

A::A()
B::B()
catch (B &ex)
B::Foo()


http://liveworkspace.org/code/2tfImF$11

Добавлено через 9 минут и 2 секунды
Только сейчас спонимаю, что плюсы это ЖЕСТЬ

Автор: volatile 14.1.2013, 23:59
Цитата(Alca @  14.1.2013,  16:47 Найти цитируемый пост)
Только сейчас спонимаю, что плюсы это ЖЕСТЬ

Гы.. smile Да уж... Но, тем не менее, всё правильно.
Цитата(ISO/IEC 14882:2011)
15.3.3
A handler is a match for an exception object of type E if
  — The handler is of type cv T or cv  T&  and  E  and  T  are  the  same  type
    (ignoring the top-level cv-qualifiers), or
  — the handler is of type cv T or cv T& and T is an  unambiguous  public  base
    class of E
, or
  — the handler is of type cv1 T* cv2 and E is  a  pointer  type  that  can  be
    converted to the type of the handler by either or both of
     — a standard pointer conversion (4.10) not involving conversions to  pointers
       to private or protected or ambiguous classes
     — a qualification conversion
  — the handler is a pointer or pointer to member type and E is std::nullptr_t.


Alca, лучше ловить сначала детей, потом родителей, потом дедушек и т.д.
Ну или, как вариант, ловить только самого старшего прадедушку, а в обработчике задействовать виртуализацию.
(главное, в последнем случае, не забыть про паблик наследование.)

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)