将成员函数声明为友元:Lippman第5版相关内容是否有误?
Yep, there's a critical compile-time issue with the code snippet you shared from Lippman's C++ Primer 5th Edition (ISBN-13: 978-0321714114) pages 280-281. Let’s walk through why and how to fix it:
The Core Problem: Missing Required Forward Declarations
When you write friend void Window_mgr::clear(ScreenIndex); inside the Screen class, the compiler has no prior knowledge of:
- What the
Window_mgrclass even is (it hasn’t been declared yet) - That
Window_mgrhas a member function namedclearthat takes aScreenIndexparameter
Without these pieces of information, the compiler will throw errors like 'Window_mgr' has not been declared or invalid use of incomplete type 'class Window_mgr'.
The Corrected Code Structure
To make this work, you need to add forward declarations in the right order:
// Forward declare the Screen class first (since Window_mgr's clear function references it) class Screen; // Declare the Window_mgr class and its clear member function class Window_mgr { public: using ScreenIndex = size_t; // Assume ScreenIndex is defined here (adjust if it's a Screen member type) void clear(ScreenIndex); }; // Now define the Screen class with the valid friend declaration class Screen { // The compiler now knows Window_mgr exists and has a clear function, so this is legal friend void Window_mgr::clear(Window_mgr::ScreenIndex); // Screen's member variables and functions go here // ... }; // Finally, implement the Window_mgr::clear function (now that Screen is fully defined) void Window_mgr::clear(ScreenIndex idx) { // Access Screen's private members here (allowed by the friend declaration) // ... }
If ScreenIndex is a member type of Screen (e.g., using ScreenIndex = size_t; inside Screen), you’ll need to adjust the order slightly—you’d declare Screen first, then Window_mgr with a function that uses Screen::ScreenIndex (though defining ScreenIndex outside both classes is often simpler to avoid circular dependency headaches).
Why the Book’s Snippet Might Look "Wrong"
Lippman’s example is likely focusing on the concept of declaring a specific member function as a friend (rather than the entire class), so it omits the boilerplate forward declarations to keep the example concise. In real-world code, though, those declarations are mandatory for the code to compile.
内容的提问来源于stack exchange,提问作者user2865249

