首页 > 解决方案 > Effective C++ (3rd edition) Item 4 代码布局

问题描述

在 Scott Meyers 的Effective C++: 55 Specific Ways to Improvement Your Programs and Designs(第 3 版)中,他在第 4 项中描述了在不同翻译单元中定义的非本地静态对象的初始化如何崩溃,并提供了一堆示例代码。

但是,我对代码布局感到困惑,应该是什么?

我试过的:

而在执行g++ directory.cpp fileSystem.cpp的时候,结果是这样的:

directory.cpp: In constructor ‘Directory::Directory()’:
directory.cpp:7:25: error: ‘tfs’ was not declared in this scope
    7 |     std::size_t disks = tfs.numDisks();
      |   

#include对 C++ 中的内容有些不安,我希望它不会妨碍我理解有效 C++ 第 4 条中示例代码的正确布局。

标签: c++includeeffective-c++

解决方案


您需要extern FileSystem tfs;从头fileSystem.cpp文件移动fileSystem.h到能够编译它。

如果应该可以链接它,您还需要在fileSystem.cpp.

文件系统.h

extern FileSystem tfs;

文件系统.cpp

FileSystem tfs;

推荐阅读