首頁 > 後端開發 > 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學習者快速成長!