我的头文件如下所示:
// method.h
class Class {
public:
string Method(const int number);
};
我的cc文件看起来像这样
// method.cc
#include "method.h"
namespace {
const char kImportantString[] = "Very long and important string";
}
string Class::Method(const int number) {
[... computation which depends on kImportantString ...]
return some_string;
}
现在,对于某些输入,Method()
应返回kImportantString
,
但对于其他输入,它不能返回kImportantString
因此,我想创建一个测试文件,如下所示:
// method_test.cc
#include "method.h"
void Test() {
assert(Method(1) == kImportantString); // kImportantString is not visible
assert(Method(2) != kImportantString); // in this file, how to fix this?
}
但目前问题是kImportantString
不在method_test.cc
档的范围内。
kImportantString
添加到method.h
并不理想,因为在头文件中不需要它。kImportantString
复制到测试文件中并不理想,因为字符串很长,后来有人可能会在一个文件中意外更改它,而不是另一个文件。因此,我的问题是:
什么是使kImportantString在测试文件中可见的最佳方法,并且在尽可能多的其他地方不可见?
答案 0 :(得分:0)
您可以在头文件中添加extern
声明,例如
extern const char kImportantString[];
然后将实际定义保留在.c
文件中。这将允许测试程序访问字符串,而不必将整个事物复制到标题中。
如果你想将它完全从标题中删除,而不是将其复制到测试文件中,你也可以只创建一个特殊的头文件,如kImportantString.h
并将extern
声明放入那里。
另一种选择是在测试文件中计算字符串的哈希,然后只比较哈希值。但这可能比它的价值更麻烦。