c++ - Effective C++ (3rd edition) Item 4 代码布局
问题描述
在 Scott Meyers 的Effective C++: 55 Specific Ways to Improvement Your Programs and Designs(第 3 版)中,他在第 4 项中描述了在不同翻译单元中定义的非本地静态对象的初始化如何崩溃,并提供了一堆示例代码。
但是,我对代码布局感到困惑,应该是什么?
我试过的:
fileSystem.h
#include <iostream> class FileSystem { public: std::size_t numDisks() const; };
fileSystem.cpp
#include "fileSystem.h" std::size_t FileSystem::numDisks() const { return 1; } extern FileSystem tfs;
directory.h
class Directory { public: Directory(); };
directory.cpp
#include <iostream> #include "fileSystem.h" #include "directory.h" Directory::Directory() { std::size_t disks = tfs.numDisks(); std::cout << disks << std::endl; } Directory tempDir; int main() { return 0; }
而在执行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 条中示例代码的正确布局。
解决方案
您需要extern FileSystem tfs;
从头fileSystem.cpp
文件移动fileSystem.h
到能够编译它。
如果应该可以链接它,您还需要在fileSystem.cpp
.
文件系统.h
extern FileSystem tfs;
文件系统.cpp
FileSystem tfs;
推荐阅读
- vb.net - TableAdapter.insert - 获取 ID(使用 SCOPE_IDENTITY)?(SQL 服务器)
- c# - 如何使用 (in) 一键 c# 在 listBox 中读取和搜索多个 txt 文件?
- sql-server - 修改棘手的外部 SQL 查询
- android - 如何隐藏我的 Android 应用程序在加载时显示的“InstanceID 令牌:”框
- flow-project - 尝试将 Aimsun 与 Flow 结合使用时出现错误“没有名为 flow 的模块”
- jquery - 如何将处理程序添加到 JQuery 中动态创建的 tr?
- c# - 使用 Azure Functions 自动将 Excel 保存为 CSV
- python - 为什么我的代码返回空白?(用 Scrapy 刮)
- sql - 不可能完成的任务?针对多个服务器上的分片数据库的智能视图
- javascript - Changing text of HTML