Classes and variables scope in C++

后端 未结 6 1546
一整个雨季
一整个雨季 2020-12-22 06:32
class car {
    int speed; 
    double position;

    public:
       car(int v,double d);
       int getspeed();
};

int car::getspeed() {
return speed;
}

car::car(         


        
6条回答
  •  粉色の甜心
    2020-12-22 07:05

    This constructor doesn't work

    car::car(int speed, double position){
       speed=speed;
       position=position;
    }
    

    because it assigns the parameters to themselves.

    This version does work because of the slightly odd scoping rules of a class

    car::car(int speed, double position) : speed(speed), position(position)
    {  }
    

提交回复
热议问题