C++ 命名空间、内部类和运算符解析

标签 c++ namespaces global operator-keyword

在 C++ 命名空间中 myspace我有一个类Outer它又有一个内部类 Inner .虽然我可以声明和定义全局友元运算符 QDataStream& operator<<(QDataStream& s, const myspace::Outer& o) ,我看不到如何声明全局友元运算符 QDataStream& operator<<(QDataStream& s, const myspace::Outer::Inner& o) .注释掉的行表示失败的尝试。我看不出如何在不定义外部类的情况下声明内部类。

namespace myspace {
    class Outer;
    //class Outer::Inner;
}

QDataStream& operator<<(QDataStream& s, const myspace::Outer& o);
//QDataStream& operator<<(QDataStream& s, const myspace::Outer::Inner& o);


namespace myspace {

    class Outer {

        friend QDataStream& (::operator <<)(QDataStream&, const Outer&);

        class Inner {
            //friend QDataStream& (::operator <<)(QDataStream&, const Inner&);
            int i;
        };

        int o;
    };

}

我读过 Namespaces and operator resolution , C++ Defining the << operator of an inner class , Accessing private class in operator<< in namespaceOperator overloading, name resolution and namespaces , 但似乎都不起作用。

如果我取消注释这些行,第一行会给出错误消息“outer.h:7: error: 'Inner' in 'class myspace::Outer' does not name a type 类外层::内层; ^" 这似乎是关键。我不能声明内部类。

我正在使用 C++ 11。

这个问题不是 Forward declaration of nested types/classes in C++ 的重复问题如果没有前向引用也能解决。

最佳答案

鉴于时间流逝,我发布了 Andreas H 给​​出的正确答案。

namespace myspace {
class Outer {
    class Inner {
        friend QDataStream& operator<<(QDataStream&, const Inner&);
        int i;
    };
    friend QDataStream& operator<<(QDataStream&, const Outer&);
    friend QDataStream& operator<<(QDataStream&, const Inner&);
    int o;
};
QDataStream& operator<<(QDataStream& s, const myspace::Outer& o) {
    s << o.o;
    return s;
}
QDataStream& operator<<(QDataStream& s, const myspace::Outer::Inner& i) {
    s << i.i;
    return s;
}
}

关于C++ 命名空间、内部类和运算符解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45335075/

相关文章:

使用变量时的 PHP 全局访问问题

c++ - 使用 C++ 迭代器从文件中读取列表?

c++ - 另一个类的成员函数中的另一个类的对象

带有命名空间的 Python xml 解析器

namespaces - 是否有适合引用存档中的文件的命名方案?

node.js - 这是创建全局 const 变量的正确方法吗?

.net - .NET 中的全局导入/使用别名

C++ 初始化列表 - 我不明白

c++ - 需要一个散列函数来从 ipv6 16 字节地址和 TCP 2 字节端口号中创建 32 位值

namespaces - 什么是命名空间污染?