方法无法访问相同类的成员变量(C ++) [英] A method can't access a member variable of the same class (C++)

查看:53
本文介绍了方法无法访问相同类的成员变量(C ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个简短的程序来说明我的学校项目的继承原理,但是我遇到了一个奇怪的问题。这是我的代码:(我已经省略了所有不是问题的代码)

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;
}

这是构建日志:

||=== 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)) ===|

我不知道此错误的含义,希望有人可以帮助我。 / p>

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

推荐答案

该函数应作为 Car 类的成员编写/ p>

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

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

您编写它的方式无法访问任何成员 Car 中的变量,因为它与您在类中声明的函数不同。

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.

这篇关于方法无法访问相同类的成员变量(C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆