Według standardu C++,Wewnętrzna widoczność członkiem klasy
9.2 [class.mem]:
A class is considered a completely-defined object type (3.9) (or complete type) at the closing } of the class-specifier. Within the class member-specification, the class is regarded as complete within function bodies, default arguments, using-declarations introducing inheriting constructors (12.9), exception-specifications, and brace-or-equal-initializers for non-static data members (including such things in nested classes). Otherwise it is regarded as incomplete within its own class member-specification
więc poniższy kod należy skompilować i rzeczywiście robi
struct Foo{
Foo()
{
Bar bar; // Bar is fully visible here, even though it's defined later
}
//void f(Bar){} // But NOT VISIBLE if used as a function parameter
struct Bar{};
};
int main()
{
Foo foo;
}
Jednak gdybym odkomentowaniu linia definiująca funkcję składową void Foo::f(Bar)
, a następnie kod nie skompiluje się z błędem
error: 'Bar' has not been declared
Ponownie czytając standard wydaje się, że parametry funkcji nie są uważane za miejsca, w których klasa jest uważana za kompletną. Jednak nie ma to żadnego sensu. Czy możesz rzucić trochę światła, dlaczego nie mogę użyć Bar
w parametrze funkcji (ale poza tym można go w pełni wykorzystać wewnątrz funkcji bez żadnych problemów) przed jej pełną definicją?
My najlepiej zgadnąć, że sama funkcja jest "oceniana" po zakończeniu "struct Foo", dzięki czemu dostępna jest opcja 'Bar'. Na deklaracji funkcji musi on znać typ, aby móc wygenerować sygnaturę funkcji. Ten sam problem występuje podczas definiowania typedef po próbie użycia tego typu w deklaracji funkcji. – RedX
To pytanie dotyczy raczej wyszukiwania nazw niż kompletności typu klasy. –
@RedX and T.C., Widzę teraz, uważam, że masz rację. Jeśli możesz opublikować odpowiedź, chętnie ją zaakceptuję. – vsoftco