向前声明std命名空间中的变量/类 [英] Forward Declaration of variables/classes in std namespace

查看:191
本文介绍了向前声明std命名空间中的变量/类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通常主要使用forward声明,如果我有一个类,不需要完整的定义在.hpp文件

I usually use forward declaration predominantly, if I have a class that does not need complete definition in .hpp file

Ex)

 //B.hpp

 namespace A_file {
   class A;
 }

 namespace B_file {

  class B {
   public:
        B();
   private:
        A *ptr_to_A;
  }
 }

 //B.cpp

 #include "A.hpp"
 using namespace A_file;

 namespace B_file {

   B(int value_) {
        *ptr_to_A = new A(value_);
   }

   int some_func() {
        ptr_to_A->some_func_in_A();
   }
 }

我写这种代码。我认为,它会保存包括整个hpp再次。 (如果你的话,这是不健康的)

I write this kind of code. I think, it will save including the whole hpp again. (Feel free to comment, if you thing, this is not healthy)

有没有办法,我可以做同样的对象/类在std命名空间?

Is there a way that I can do the same for objects/classes in std namespace? If there is a way, is it okay or does it have side effects?

推荐答案

你可以转发声明你的在头文件中保存自己的类以保存编译时间。但是你不能在命名空间std中的类。根据C ++ 11标准,17.6.4.2.1:

You can forward declare your own classes in header files to save compilation time. But you can't for classes in namespace std. According to the C++11 standard, 17.6.4.2.1:


C ++程序的行为是未定义的,如果它添加声明或
对命名空间std的定义或命名空间std
中的命名空间除非另有规定。

The behavior of a C++ program is undefined if it adds declarations or definitions to namespace std or to a namespace within namespace std unless otherwise specified.

这些类是模板类的typedef,因此一个简单的向前声明将不起作用。例如,您可以使用#include< iosfwd> 而不是#include< iostream> string 向量等。

Note that some of these classes are typedefs of templated classes, so a simple forward declaration will not work. You can use #include<iosfwd> instead of #include<iostream> for example, but there are no similar headers with just forward declarations for string, vector, etc.

有关详情,请参阅 GotW#34,转发声明

这篇关于向前声明std命名空间中的变量/类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆