阴影变量 [英] Shadowing variables
问题描述
我的问题是关于变量定义到类。我告诉你我的问题。
My question is about variables defined into classes. I show you my problem.
我已经定义了这个类:
class Measure {
int N;
double measure_set[];
char nomefile[];
double T;
public:
void get( );
void printall( );
double mean( );
double thermal_comp( );
};
我想要方法get执行以下操作:
I would like method get to do the following:
- 从.dat文件读取数字并保存到measure_set数组中;
- 读取用户输入并将其保存到变量T中;
这是我所做的:
void Measure::get()
{
cout << "Insert filename:" << endl;
cin >> nomefile;
cout << endl;
cout << nomefile << endl;
cout << endl;
int M=0;
int nmax=50;
ifstream f;
f.open(nomefile);
while(M<nmax)
{
f >> measure_set[M];
if(f.eof())
break;
M++;
}
f.close();
N=M+1;
cout << "Insert temperature:" << endl;
cin >> T;
cout << endl;
}
会发生什么是我注意到T被记住在 measure_set [0]
。为什么会发生这种情况,如何写一个工作代码?我不是C ++的专家,使用这只是为了计算的目的,虽然我可以解决我的问题在其他方式我想学习如何使这工作在C + +。非常感谢!
What happens is that I've noticed that T is memorized in measure_set[0]
. Why this happens and how can I write a working code? I'm not that expert in C++, using this only for computation purposes, although I could solve my problem in other ways I would like to learn how to make this work in C++. Thanks a lot!
推荐答案
在C和C ++中,同一个名称在多个范围内使用是合法的 - (例如gcc -Wshadow)会提供一个机制来警告你,因为它可能导致混乱。
In both C and C++ it is legal for the same name to be used within multiple scopes - some compilers (e.g. gcc -Wshadow) will provide a mechanism that warns you about this since it can cause confusion.
#include <iostream>
int i = 0;
int main() {
int i = 1;
for (int i = 0; i < 10; ++i) {
int i = 2 * i;
std::cout << i << std::endl;
}
return 0;
}
一些编译器将编译此输出'0,2,4,6, 8,...。 有些不会。
Some compilers will compile this and output '0, 2, 4, 6, 8, ...'. Some won't.
避免的常见方式这是使用前缀。 m_表示成员,s_表示静态,g_表示全局等。一些编码样式对成员变量使用_后缀。这也有助于保持成员变量不与类似命名的getters / setters冲突,如果这是你的骆驼滚动。
A common way to avoid this is to use prefixes. "m_" for "member", "s_" for "static", "g_" for "global", etc. Some coding styles use a "_" suffix for member variables. This also helps to keep member variables from clashing with similarly named getters/setters if that's the way your camel rolls.
class Measure {
int m_n;
double m_measureSet[MEASURE_SET_SIZE]; // [] is not legal in a class.
std::string m_nomefile;
double m_t;
public:
const std::string& nomefile() const { return m_nomefile; }
...
};
在这种情况下,在使用中,我倾向于发现开发人员使用访问器比起成员(在开头比类型m_更容易添加())。
Where this pays off is in the usage, I tend to find developers are encouraged to use the accessors rather than the members (it seems to be easier to add () at the end than type "m_" at the beginning).
std::cout << "Measuring file " << nomefile << std::endl;
会成为
std::cout << "Measuring file " << m_nomefile << std::endl;
或更佳:
std::cout << "Measuring file " << nomefile() << std::endl;
这篇关于阴影变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!