相关疑难解决方法(0)

我如何转发声明内部类?

可能重复:
在C++中转发嵌套类型/类的声明

我有一个这样的课......

class Container {
public:
    class Iterator {
        ...
    };

    ...
};
Run Code Online (Sandbox Code Playgroud)

在其他地方,我想通过引用传递一个Container :: Iterator,但我不想包含头文件.如果我尝试转发声明类,我会遇到编译错误.

class Container::Iterator;

class Foo {
    void Read(Container::Iterator& it);
};
Run Code Online (Sandbox Code Playgroud)

编译上面的代码给出了......

test.h:3: error: ‘Iterator’ in class ‘Container’ does not name a type
test.h:5: error: variable or field ‘Foo’ declared void
test.h:5: error: incomplete type ‘Container’ used in nested name specifier
test.h:5: error: ‘it’ was not declared in this scope
Run Code Online (Sandbox Code Playgroud)

我怎样才能转发声明这个类,所以我不必包含声明Iterator类的头文件?

c++ forward-declaration

145
推荐指数
2
解决办法
8万
查看次数

为什么C++好友类只需要在其他命名空间中使用前向声明?

假设我有一个类F应该是类G(在全局命名空间中)和C(在命名空间中A)的朋友.

  • 要成为朋友A::C,F必须向前宣布.
  • 要成为朋友G,没有F必要的前瞻性声明.
  • 同样,一个班级A::BF可以成为朋友而A::C无需前瞻性声明

下面的代码说明了这一点,并使用GCC 4.5,VC++ 10以及至少与另一个编译器进行编译.

class G {
    friend class F;
    int g;
};

// without this forward declaration, F can't be friend to A::C
class F;

namespace A {

class C {
    friend class ::F;
    friend class BF;
    int c;
};

class BF {
public:
    BF() { c.c = 2; }
private:
    C c;
};

} // …
Run Code Online (Sandbox Code Playgroud)

c++ namespaces friend forward-declaration

46
推荐指数
2
解决办法
3万
查看次数

何时使用命名空间或结构?

我只是从http://www.cplusplus.com/doc/tutorial/namespaces/上阅读了一些内容 ,它看起来像一个结构体能够做同样的事情?或者甚至是一个类.也许有人可以更好地定义命名空间是什么,以及它与结构/类的区别?

c++ struct namespaces

11
推荐指数
3
解决办法
1万
查看次数

标签 统计

c++ ×3

forward-declaration ×2

namespaces ×2

friend ×1

struct ×1