ホームページ  >  記事  >  バックエンド開発  >  ## C クラスの意図した変数ではなく、温度値が配列に格納されているのはなぜですか?

## C クラスの意図した変数ではなく、温度値が配列に格納されているのはなぜですか?

Barbara Streisand
Barbara Streisandオリジナル
2024-10-25 00:27:30946ブラウズ

## 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) が、意図した T ではなく、measure_set 配列 (measure_set[0]) の最初の要素に格納されていることがわかります。 variable.

Solution

これは、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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。