阴影变量

Val*_*ini 1 c++

我的问题是关于定义到类中的变量.我告诉你我的问题.

我已经定义了这个类:

class Measure {

int N;
double measure_set[];
char nomefile[];
double T;

public:
    void get( );
    void printall( );
    double mean( );
    double thermal_comp( );
};
Run Code Online (Sandbox Code Playgroud)

我想方法得到以下内容:

  1. 从.dat文件中读取数字并保存到measure_set数组中;
  2. 读取用户输入并将其保存到变量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;
} 
Run Code Online (Sandbox Code Playgroud)

会发生什么事情,我注意到T被记忆了measure_set[0].为什么会发生这种情况?如何编写有效的代码?我不是C++方面的专家,仅将其用于计算目的,虽然我可以通过其他方式解决我的问题,但我想学习如何在C++中使用它.非常感谢!

kfs*_*one 6

在C和C++中,在多个范围内使用相同名称是合法的 - 一些编译器(例如gcc -Wshadow)将提供一种警告您的机制,因为它可能导致混淆.

#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;
}
Run Code Online (Sandbox Code Playgroud)

一些编译器将编译它并输出'0,2,4,6,8 ......'.有些人不会.

避免这种情况的常见方法是使用前缀."m_"表示"成员","s_"表示"静态","g_"表示"全局"等.某些编码样式对成员变量使用"_"后缀.这也有助于防止成员变量与类似命名的getter/setter冲突,如果这是你的骆驼滚动的方式.

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; }
    ...
};
Run Code Online (Sandbox Code Playgroud)

如果这种回报在使用中,我倾向于发现鼓励开发人员使用访问者而不是成员(最后添加()似乎比在开头键入"m_"更容易.

std::cout << "Measuring file " << nomefile << std::endl;
Run Code Online (Sandbox Code Playgroud)

会成为

std::cout << "Measuring file " << m_nomefile << std::endl;
Run Code Online (Sandbox Code Playgroud)

或更好:

std::cout << "Measuring file " << nomefile() << std::endl;
Run Code Online (Sandbox Code Playgroud)