簡體   English   中英

請解釋該類構造函數的輸出

[英]Please explain the output of this class constructor

#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放在班級的私有部分並且運行良好時,但我想知道因為我將其放在類的私有部分中並且主函數可以看到它,所以我沒有得到另一個錯誤嗎?

您的基本概念有問題,因為您使用的是局部變量( int speed ),一旦離開函數,它們就會失去其值。 您最可能想要的是一個成員變量(就像df_speed一樣)。

構造函數中的輸出是正確的,因為您可以通過兩種方式設置該值。

但是,由於在賦值/計算中使用未初始化的變量( speed ),因此tricie::acc()tricie::deacc()的輸出未定義。

您的代碼中有錯誤。 您在所有函數(構造函數, acc()deacc() )中重新聲明speed變量,例如在deacc()

int speed=(speed+1);

最初的speed是未聲明的(在此范圍內),但是您可以用它減去1 (完全)這是未定義的行為。

要解決此問題,請在以下三種情況下刪除變量聲明( int ),然后向該類中添加一個類變量以存儲當前速度:

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_speed 但這取決於df_speed的含義(可能在您的書中有所描述..?)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM