-3

如何访问被覆盖的基类函数中的成员变量?

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

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

ThisClass::keyPressed = true;

我究竟做错了什么?

//添加的细节------------------------------ -------------

这个类.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.
}

基类.h:

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

基类.cpp

include 'BaseClass.h"

void BaseClass::handleNotification(s3eKey key) {
}
4

2 回答 2

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的变量。

于 2014-08-26T17:00:13.393 回答
1

The correct way to override a function is as follows.

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
}

edit Note that base::some_func() and derived::some_func() are two different functions, with the latter overriding the former.

于 2014-08-26T17:19:10.080 回答