Classes and variables scope in C++

后端 未结 6 1533
一整个雨季
一整个雨季 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 06:46

    In the second case, I believe the closest scope variable is used. So, first it checks the local function scope, and finds both speed and position, so the search stops there. In effect, the second constructor isn't actually assigning obje

    0 讨论(0)
  • 2020-12-22 06:51

    The names of parameteres are not important. Types of parameteres create the signature. The signature is the same, so there is no compile error.

    In second example speed in constructor will shadow speed atribute. Therefore you will assign parameter value to parameter variable. You need:

    this->speed = speed;

    And this is not guesswork ;-).

    0 讨论(0)
  • 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->

    0 讨论(0)
  • 2020-12-22 06:59
    car::car(int speed, double position){
       speed=speed;
       position=position;
    }
    

    In this function definition, it does nothing with the class member car::speed, and car::position, because you declared the local int speed and double position in the function parameter list, they hide the class member variables. To do it properly, you need explicitly say so:

    car::car(int speed, double position){
       this->speed=speed;
       this->position=position;
    }
    
    0 讨论(0)
  • 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)
    {  }
    
    0 讨论(0)
  • 2020-12-22 07:06

    The compiler doesn't care about your variable names in the method declaration, just the signature, which is

    car::car(int,double)

    for both your constructor declaration and your implementation, so it knows to match these up when linking. This is possible because you cannot have two methods in the class with the same signature. (You can do this with subclasses, but the result is an override).

    0 讨论(0)
提交回复
热议问题