0
#include <iostream>

using namespace std;

class tricie
{
public:
    tricie(int);
    ~tricie();
    void acc();
    void deacc();
private:
    int df_speed=8;
};

tricie::tricie(int speed_input)                //Shouldn't this make the speed=8?
{
    int speed;
    if (speed_input > df_speed)
    {
        speed=speed_input;
        cout<<"speed now is "<<speed<<" km/hr \n";
    }
    else
    {
        speed=df_speed;
        cout<<"speed now is "<<speed<<" km/hr \n";
    }
}
tricie::~tricie()
{

}
void tricie::acc()
{
    int speed=(speed+1);
    cout<<"speed now is "<<speed<<" km/hr \n";
}
void tricie::deacc()
{
    int speed=(speed-1);
    cout<<"speed now is "<<speed<<" km/hr \n";
}
int main(int argc, const char * argv[])  //Xcode but these stuff in the bracket (ignore)
{
    tricie biker1(4);          //If i put any number > 8 the program work correctly
    biker1.acc();              //output from this line is "speed now is 5 km/hr "    instead of 9
    biker1.deacc();            //output from this line is "speed now is 4 km/hr "    instead of 8
    biker1.deacc();            //output from this line is "speed now is 3 km/hr "    instead of 7
    return 0;
}

出力 8 5 4 3 が 8 9 8 7 ではない理由を説明する概念が欠けているかどうかを知りたいですか?

前もって感謝し、質問がばかげている場合は申し訳ありませんが、samsを使用して独学しています.24時間の本でc ++を教えます.

迅速な対応をありがとうございました。これらの場合にコンパイルを防ぐ方法があるかどうかを検索します。フォローアップの質問があります。クラスのプライベート部分に int speed を配置し、正常に動作していますが、知りたいですクラスのプライベート部分に入れ、メイン関数がそれを見ることができるので、私が取得していない別のエラーはありますか?

4

2 に答える 2

2

int speed関数を終了すると値が失われるローカル変数 ( ) を使用しているため、基本的な概念に問題があります。最も可能性が高いのはメンバー変数です (のようにdf_speed)。

いずれかの方法で値を設定したため、コンストラクターの出力は正しいです。

ただし、割り当て/計算で初期化されていない変数 ( ) を使用しているため、tricie::acc()andの出力は未定義です。tricie::deacc()speed

于 2013-01-29T11:54:29.600 に答える
2

コードにエラーがあります。たとえば、次のようにspeed、すべての関数 (コンストラクター、acc()およびdeacc()) で変数を再宣言します。deacc()

int speed=(speed+1);

最初speedは(このスコープで)宣言されていませんが、それを使用してそれから減算1します。これは(完全に)未定義の動作です。

これを修正するにはint、次の 3 つの状況で変数宣言 ( ) を削除し、現在の速度を格納するクラス変数をクラスに追加します。

class tricie {
  //...
  int speed;
  //...
}

void tricie::deacc()
{
    speed=(speed-1);
    cout<<"speed now is "<<speed<<" km/hr \n";
}

コンストラクターの場合と同じで、完全acc()に削除されint speed;ます。

注: 私df_speedは、(d)「デフォルトの速度」と仮定します。実際の速度を保持する必要があるのがクラス変数である場合は、すべてのspeed変数の使用箇所の名前を に変更する必要がありますdf_speeddf_speedしかし、これは(おそらくあなたの本に記載されている..?)の意味に依存します.

于 2013-01-29T11:54:56.443 に答える