我可以从派生类中的静态函数访问基类受保护成员吗?
我有一个程序,需要创建一个在 dll 和一些应用程序代码之间共享的基类。然后我有两个不同的派生类,一个在 dll 中,一个在主应用程序中。其中每个都有一些静态成员函数,它们对 nase 类中的数据进行操作。 (它们需要是静态的,因为在其他地方用作函数指针)。我的问题以最简单的形式如下所示。
class Base {
protected:
int var ;
};
class Derived : public Base {
static bool Process( Base *pBase ) {
pBase->var = 2;
return true;
}
};
我的编译器抱怨我无法访问 pBase 的受保护成员,即使 Derived 对 Base 具有受保护的访问权限。有什么办法可以解决这个问题还是我误解了什么? 我可以将基本变量公开,但这会很糟糕,因为在我的实际实例中,这些是分配的内存块和保护它进行多线程的信号量。
帮助?
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;
}
};
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.
Help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一般来说(无论函数是否是静态的),
派生类的成员函数只能访问受保护的基类
其类型的对象的类成员。它无法访问受保护的
如果静态类型不是派生类的静态类型,则为基类成员
(或从它派生的类)。所以:
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:
访问说明符适用于
Derived
类句柄(引用/指针/对象),而不适用于Derived
类本身的方法。即使该方法不是静态
,您也会遇到相同的错误。因为您没有使用派生句柄访问var
。 演示。正确的方法是提供一个
setter
方法:注意:还有一种方法,但我不确定它是否优雅。
Access specifier applies to the
Derived
class handle (reference/pointer/object) and not the methods ofDerived
class itself. Even if the method was notstatic
, you would have ended up with the same error. Because you are not accessingvar
with the derived handle. Demo.The correct way is to provide a
setter
method:Note: There is one more way out, but I am not sure if it's elegant.
您可以使派生类成为基类的朋友
You can make the derived class friend of your base class