如果我有一个不需要在 .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/