我可以从派生类中的静态函数访问基类受保护的成员吗? [英] Can I access a base classes protected members from a static function in a derived class?

查看:254
本文介绍了我可以从派生类中的静态函数访问基类受保护的成员吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序,我需要做一个基类,它是一个dll和一些应用程序代码之间共享。然后我有两个不同的派生类,一个在dll一个在主应用程序。每个都有一些静态成员函数,对nase类中的数据进行操作。 (它们需要是静态的,因为在其他地方用作函数指针)。在最简单的形式中,我的问题如下所示。

I have a program where I need to make a base class which is shared between a dll and some application code. Then I have two different derived classes, one in the dll one in the main application. Each of these have some static member functions which operate on the data in the nase class. (They need to be static as are used as function pointers elsewhere). In its simplest form my issue is shown below.

class Base {
protected:
  int var ;
};

class Derived : public Base {
  static bool Process( Base *pBase ) {
    pBase->var = 2;
    return true;
  }
};



我的编译器抱怨我不能访问pBase的受保护成员,即使Derived已经保护对Base的访问。有什么办法绕过这个或者我误会了什么?
我可以使基本变量公开,但这将是坏的,因为在我的实例,这些是一个分配的内存块和信号量保护它的多线程。

My compiler complains that I cannot access protected members of pBase even though Derived has protected access to Base. Is there any way around this or am I misunderstanding something? I can make the Base variables public but this would be bad as in my real instance these are a lump of allocated memory and the semaphores to protect it for multithreading.

帮助?

推荐答案

一般来说(无论函数是否是静态的),一个
成员函数的派生类只能访问其类型的对象的受保护的基本
类成员。如果静态类型不是派生类
(或从其派生的类)的静态类型,则它不能访问受保护的
基本成员。所以:

In general (regardless of whether the function is static or not), a member function of the derived class can only access protected base class members of objects of its type. It cannot access protected members of the base if the static type is not that of the derived class (or a class derived from it). So:

class Base {
protected:
    int var;
 } ;

class Derived : public Base {
    static void f1( Derived* pDerived )
    {
        pDerived->var = 2; // legal, access through Derived...
    }
    static bool Process( Base *pBase )
    {
        pBase->var = 2 ;  // illegal, access not through Derived...
    }
} ;

这篇关于我可以从派生类中的静态函数访问基类受保护的成员吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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