c++ - std 命名空间中变量/类的前向声明

标签 c++ class std forward-declaration

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

例)

 //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。 (随意发表评论,如果你不满意,这不健康)

有没有一种方法可以对 std 命名空间中的对象/类执行相同的操作? 如果有办法好不好,有没有副作用?

最佳答案

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

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>例如,但没有类似的 header 只有 string 的前向声明, vector

参见 GotW #34, Forward Declarations获取更多信息。

关于c++ - std 命名空间中变量/类的前向声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10289766/

相关文章:

c++ - 在C++中找出无限范数的相对误差

c++ - 一个数组来保存 C++ 中的任何对象?

python - 从类元素中创建 python 列表的副本

C++ 通过访问器返回一个字符串

c++ - 如何比较两个 std::set?

c++ - 只接受字母

c++ - 将 wiringPi 库添加到 RaspberryPi 上的 cmake

c++ - C4512 无法生成赋值运算符

c - 为什么 Eclipse 的 C 应用程序在调用 `system("clear")`(在 stdlib.h 中定义)时启动终端打印垃圾?

c++ - 如何为用户提供针对给定 boost::spirit 语法的高级自动完成建议?