Classes and variables scope in C++

后端 未结 6 1545
一整个雨季
一整个雨季 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条回答
  •  -上瘾入骨i
    2020-12-22 06:56

    In your code:

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

    you're just assigning each variable's value to itself. You can however do:

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

    in addition to explicitly accessing the member variables via this->

提交回复
热议问题