请解释此类构造函数的输出

时间:2013-01-29 11:49:51

标签: c++ 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速度放在类的私有部分,它工作正常,但我我想知道是否还有其他错误我没有得到,因为我把它放在类的私有部分,主函数可以看到它?

2 个答案:

答案 0 :(得分:2)

你的基本概念有问题,因为你使用局部变量(int speed),一旦你离开函数就会失去它们的价值。你最想要的是一个成员变量(就像df_speed)。

构造函数中的输出是正确的,因为您可以设置值。

但是,tricie::acc()tricie::deacc()的输出未定义,因为您在分配/计算中使用了未初始化的变量(speed)。

答案 1 :(得分:2)

您的代码中有错误。您重新声明了所有函数中的speed变量(构造函数acc()deacc()),例如在deacc()中:

int speed=(speed+1);

最初speed未声明(在此范围内),但您可以使用它从中减去1。这是(完全)未定义的行为。

要解决此问题,请在这3种情况下删除变量声明(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的含义(可能在你的书中描述了......?)

相关问题