You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将成员函数声明为友元:Lippman第5版相关内容是否有误?

Is the provided Screen class friend declaration code incorrect?

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_mgr class even is (it hasn’t been declared yet)
  • That Window_mgr has a member function named clear that takes a ScreenIndex parameter

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:09:39