c++ - 编译错误 friend 类无法访问字段

标签 c++ qt qt5 friend

我正在尝试编译QT5.3
有问题的文件是 qv4executableallocator_p.h 和 qv4executableallocator.cpp。 header 中的相关代码片段如下

 struct Allocation{
    Allocation()
    : addr(0)
    , size(0)
    , free(true)
    , next(0)
    , prev(0)
    {}
    void *start() const;
    void invalidate() { addr = 0; }
    bool isValid() const { return addr != 0; }
    void deallocate(ExecutableAllocator *allocator);
    private:
        ~Allocation() {}
        friend class ExecutableAllocator;
        Allocation *split(size_t dividingSize);
        bool mergeNext(ExecutableAllocator *allocator);
        bool mergePrevious(ExecutableAllocator *allocator);
        quintptr addr;
        uint size : 31; // More than 2GB of function code? nah :)
        uint free : 1;
        Allocation *next;
        Allocation *prev;
};  

在 cpp 函数 ExecutableAllocator::ChunkOfPages::~ChunkOfPages() 中,我在尝试访问 alloc->next 时遇到编译错误。

QV4::ExecutableAllocator::Allocation* QV4::ExecutableAllocator::Allocation::next’ is private

代码可以在线查看 https://qt.gitorious.org/qt/qtdeclarative/source/be6c91acc3ee5ebb8336b9e79df195662ac11788:src/qml/jsruntime

我的gcc版本比较旧... 4.1
这是问题还是我的环境中有其他问题。我想要一种前进的方式。我坚持使用这个编译器,因为它是我必须在我的目标平台上使用的编译器

最佳答案

我猜 QV4::ExecutableAllocator::ChunkOfPages 结构没有直接与 Allocation 成为 friend ,所以你不能访问 Allocation 在 C++11 标准之前的 C++ 析构函数中的私有(private)数据。

尝试将 friend struct ExecutableAllocator::ChunkOfPages 添加到 Allocation 定义中,这应该可以解决问题。

在 C++11 中处理嵌套类的方式略有变化(引用自 cppreference.com ):

Prior C++11, member declarations and definitions inside the nested class of the friend of class T cannot access the private and protected members of class T, but some compilers accept it even in pre-C++11 mode.

这可以解释为什么这在新编译器中有效,但在您的旧编译器中无效。

关于c++ - 编译错误 friend 类无法访问字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27166273/

相关文章:

C++98,但 clang-tidy 说使用 nullptr?

c++ - QTreeView、QFileSystemModel、setRootPath 和 QSortFilterProxyModel 以及用于过滤的 RegExp

qt - 如何将标题设置为 QListView

c++ - 如何向 QFileSystemModel 添加自定义角色

c++ - Qt widget 推广 : whats difference btw these two codes?

android - Qt5:Android 上的原生外观小部件

c++ - 从命令行命名一个新文件

c++ - 当对象超出范围时是否调用析构函数?

C++ 不可理解的编译器错误

c++ - 在 SLOT 中动态调用函数