Olu*_*ide 14 c++ member-function-pointers private
根据最近一个问题的以下答案,我可以使用函数指针从另一个类调用私有方法,如下所示(另请参见ideone)Foo<T>::foo()Bar
#include <iostream>
template<typename T>
struct Bar
{
typedef void (T::*F)();
Bar( T& t_ , F f ) : t( t_ ) , func( f )
{
}
void operator()()
{
(t.*func)();
}
F func;
T& t;
};
template<typename T>
class Foo
{
private:
void foo()
{
std::cout << "Foo<T>::foo()" << std::endl;
}
public:
Foo() : bar( *this , &Foo::foo )
{
bar();
}
Bar<Foo<T> > bar;
};
int main()
{
Foo<int> foo;
}
Run Code Online (Sandbox Code Playgroud)
这适用于MSVC 2013和GCC 4.8.3.有效吗?
小智 17
C++标准说
11.1班级成员可以是
(1.1) - 私人; 也就是说,它的名称只能由声明它的类的成员和朋友使用.
即访问说明符应用于名称,而不是可执行代码.如果您考虑它,这是有道理的,因为访问说明符是编译时构造.
是的,它是允许的,它的工作原理.
C++防止意外而非故意规避(欺诈)
当然,你不能直接/轻松地在课堂外调用私有方法,但如果你做了足够的努力,C++将允许它.