A method can't access a member variable of the

2019-06-22 16:37发布

I wrote a short program to illustrate the principles of inheritance for my school project, but I am having a weird problem. Here is my code: (I have omitted all the code that isn't the problem)

class Car
{
protected:
    double fuelLevel;
public:
    void fuelUp(double);
};

void fuelUp(double fuel)
{
    Car::fuelLevel += fuel;
}

and this is the build log:

||=== Build: Debug in wierdError (compiler: GNU GCC Compiler) ===|
||In function 'void fuelUp(double)':|
|4|error: 'double Car::fuelLevel' is protected|
|11|error: within this context|
|4|error: invalid use of non-static data member 'Car::fuelLevel'|
|11|error: from this location|
||=== Build failed: 4 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

I have no idea about what this error means and I hope there is somebody who can help me.

4条回答
Bombasti
2楼-- · 2019-06-22 17:04

The way that you have it written Car::fuelLevel += fuel is triyng to access the variable fuelLevel as if it were static. You need to either make that variable static or, more likely what you meant to do, is make the method

void Car::fuelUp(double fuel)
{
    fuelLevel += fuel;
}

If it makes it any more clear why your original code was wrong, you could also change it to:

void Car::fuelUp(double fuel)
{
    this->fuelLevel += fuel;
}

Notice in the second variant that you are accessing the field via this->, which is implicitly happening in the first version. Your version had it accessing the field via the class Car::.

查看更多
戒情不戒烟
3楼-- · 2019-06-22 17:08

This

void fuelUp(double fuel)
{
    Car::fuelLevel += fuel;
}

is not a method. It is some function that has the same name as the method declared inside the class. This code could work if Car::fuelLevel would be public static data member of the class.

When you define a method outside a class definition you should specify the class to which the method belongs.

void Car::fuelUp(double fuel)
{
    Car::fuelLevel += fuel;
}
查看更多
Evening l夕情丶
4楼-- · 2019-06-22 17:09

That function should be written as a member of the class Car

void Car::fuelUp(double fuel)
{
    fuelLevel += fuel;
}

The way you wrote it, it does not have access to any of the member variables in Car because it is a different function than the one you declared in the class.

查看更多
放我归山
5楼-- · 2019-06-22 17:19

You must refer your function to a certain class when defining it outside the class. So you should write the Car before defining the function. It must be on the form void car::fuelUp(double fuel)

查看更多
登录 后发表回答