在重写的基类函数中访问成员变量

时间:2014-08-26 16:52:06

标签: c++ member-variables

如何在重写的基类函数中访问成员变量?

//Overridden base class function
void handleNotification(s3eKey key){
     //Member variable of this class
     keyPressed = true; //Compiler thinks this is undeclared.
}

Complier抱怨没有声明keyPressed。我可以弄清楚如何访问它的唯一方法是将keyPressed声明为公共静态变量,然后使用类似的东西:

ThisClass::keyPressed = true;

我做错了什么?

//添加了详细信息------------------------------------------- ----------------

ThisClass.h:

include "BaseClass.h"

class ThisClass: public BaseClass {
private:
    bool keyPressed;
};

ThisClass.cpp:

include "ThisClass.h"

//Overridden BaseClass function
void handleNotification(s3eKey key){
     //Member variable of ThisClass
     keyPressed = true; //Compiler thinks this is undeclared.
}

BaseClass.h:

class BaseClass{
public:
    virtual void handleNotification(s3eKey key);
};

BaseClass.cpp

include 'BaseClass.h"

void BaseClass::handleNotification(s3eKey key) {
}

2 个答案:

答案 0 :(得分:2)

此方法是否在类定义之外定义?换句话说,你的代码结构是这样的:

class ThisClass {
    ...
};

// method defined outside of the scope of ThisClass declaration, potentially
// in a completely different file
void handleNotification(s3eKey key) {
    ....
}

如果是这样,你需要声明这样的方法:

void ThisClass::handleNotification(s3eKey key){
    keyPresssed = true;
}

否则编译器将不知道正在实现的handleNotification()方法是属于ThisClass的方法。相反,它会假设ThisClass实现的一部分,因此它无法自动访问ThisClass个变量。< / p>

答案 1 :(得分:1)

覆盖函数的正确方法如下:

class base {
protected:
  int some_data;
  virtual void some_func(int);
public:
  void func(int x) { some_func(x); }
};

void base::some_func(int x)
{ /* definition, may be in some source file. */ }

class derived : public base
{
protected:
  virtual void some_func(int);  // this is not base::some_func() !
};

void derived::some_func(int x)
{
  some_data = x; // example implementation, may be in some source file
}

修改请注意,base::some_func()derived::some_func()是两个不同的功能,后者会覆盖前者。