此代碼在VS2008中生成C2248 : 'A::B::ExceptionB' : cannot access private class declared in 'class A::B'
。爲什麼編譯器不會抱怨catch子句?
#include <iostream>
class A
{
class ExceptionA{};
class B
{
class ExceptionB{};
public:
B();
};
public:
A(int);
};
A::B::B()
{
throw ExceptionB();
}
A::A(int i)
{
i % 2 ? throw ExceptionA() : throw A::B::ExceptionB(); // C2248 !!
}
int main()
{
try
{
A a(3);
}
catch(A::ExceptionA&)
{
std::cout << "A::ExceptionA" << std::endl;
}
catch(A::B::ExceptionB&)
{
std::cout << "A::B::ExceptionB" << std::endl;
}
}
當然,如果我讓類ExceptionB{}
公衆B
,代碼編譯。
但我不明白爲什麼編譯器簡化版,在main()
抱怨的2個catch子句,爲A::ExceptionA
是A
的私有類和A::B::ExceptionB
是A::B
私有類。
你說得對。如果我用'catch(A :: ExceptionA&a)'替換'catch(A :: ExceptionA&)',編譯器會抱怨。您在標準中提到了第15.6章,但我找不到它,至少在標準最新草案N3225中找不到。你能確認15.6段落1嗎? – Belloc 2012-03-11 15:27:38
@ user1042389:我在這裏查看C++ 03。 – 2012-03-11 15:31:01
謝謝。我給你的答案的功勞。 – Belloc 2012-03-11 15:33:10