C 单功能变量放置
C++ single-function variable placement
我正在编写一个从文件中读取数据的类。该项目仍在开发中,很可能会以后更改文件名或路径,因此我将其存储在std ::字符串中以进行更快编辑。
鉴于文件名将在函数中多次使用,但仅在一个函数中使用,是否有关于我应该在何处定义变量的规范CPP规则?
//don't know where I'll define this
std::string file_name = "path/to/file.foo";
//a.h file
class A {
public:
void fileFunc();
private:
//do i define it here?
};
//a.cpp file
A::fileFunc() {
//or do i define it here?
std::ifstream in(file_name);
if(in) {
//do things
}
else {
std::cerr << "couldn't open " << file_name;
}
}
将所有信息保持在Thiers使用的附近。
它将有助于可读性和性能。请参阅:https://en.wikipedia.org/wiki/locality_of_reference
so
A::fileFunc() {
const std::string file_name = "path/to/file.foo"; // pls use const when you can
...
或
A::fileFunc(const std::string& file_name) {
...
顺便说一句,我认为这应该在https://codereview.stackexchange.com/上,而不是stackoverflow。
相关文章:
- 将 2D 数组传递给大小为变量的功能
- 将非静态成员函数C 的使用无效,而将成员功能作为函数变量
- 功能原型变量范围C
- 避免为每个成员变量重复功能
- 线程安全性和静态变量/成员功能
- 功能和变量从何而来
- 无全局变量或功能参数的递归调用
- 在已经运行的功能C 中更改变量
- 将功能输出分配给变量
- 从成员变量更新类变量或调用类功能是给出运行时错误
- 如何访问C 中的功能范围变量
- 我的朋友功能无法访问私人变量
- 不同的变量和功能起作用
- 在功能中设置对象变量
- 类和本地功能变量内的全局变量
- 我需要在类C 中定义所有私人功能和变量
- 如何在Arduino的功能中提供软件变量
- 是否可以在C++中推迟 const 变量的初始化,例如 Java 的"blank final"功能?
- 无法从类中的其他功能访问同一类的变量
- 在模拟过程中更改FMI变量/功能