首页 > 后端开发 > C++ > 正文

## 为什么我的温度值存储在数组中,而不是 C 类中的预期变量?

Barbara Streisand
发布: 2024-10-25 00:27:30
原创
945 人浏览过

## Why is my temperature value being stored in the array instead of the intended variable in my C   class?

C 中的遮蔽变量

在面向对象编程中,当类中定义的变量与变量同名时,就会发生遮蔽在外部范围内。这可能会导致意外的行为,因为内部变量优先于外部变量。

问题:类中的遮蔽

考虑以下类定义:

<code class="cpp">class Measure {
    int N;
    double measure_set[];
    char nomefile[];
    double T;

    public:
    void get( );
    void printall( );
    double mean( );
    double thermal_comp( );
};</code>
登录后复制

此类中的 get 方法旨在从文件中读取值并将其保存在measure_set数组中,以及读取温度值并将其存储在T变量中。

但是,当您按如下方式实现 get 方法时:

<code class="cpp">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;
}</code>
登录后复制

您注意到温度值 (T) 存储在measure_set 数组 (measure_set[0]) 的第一个元素中,而不是预期的 T

解决方案

出现这种情况是因为C允许在不同的作用域中声明同名的变量。在这种情况下,在 get 方法中声明的 T 变量会遮蔽类成员变量 T。

为了避免遮蔽,您可以为变量使用不同的名称,或者使用作用域解析运算符 (::) 显式地引用类成员变量。

在 get 方法中为温度变量使用不同的名称将如下所示:

<code class="cpp">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;
    double temperature;  // Use a different name for the temperature variable
    cin >> temperature;
    T = temperature;
    cout << endl;
}</code>
登录后复制

使用范围解析运算符显式引用类成员变量看起来像这样:

<code class="cpp">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 >> this->T;  // Use the scope resolution operator to refer to the class member variable
    cout << endl;
}</code>
登录后复制

以上是## 为什么我的温度值存储在数组中,而不是 C 类中的预期变量?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!