能够使用指针来调用外部类的私有方法 [英] Able to use pointer to function to call private method of an external class

查看:138
本文介绍了能够使用指针来调用外部类的私有方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基于以下回答到最近的 question ,我可以使用函数指针来调用来自另一个类的私有方法 Foo< T> :: foo() Bar ,如下所示(另请参阅 ideone

Based on the following answer to a recent question, I'm able to use a function pointer in order to call the private method Foo<T>::foo() from another class Bar, as shown below (see also ideone)

#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;
}

这适用于MSVC 2013和GCC 4.8.3。

This works on MSVC 2013 and GCC 4.8.3. Is it valid?

推荐答案

是的,它是可以的,它可以工作。

Yes it is permissible, and it works.

C ++ Programming by Bjarne Stroustoup


C ++防止意外而非故意规避
(欺诈)

C++ protects against accident rather than deliberate circumvention (fraud)



<当然,你不能直接/轻松地调用类外的私有方法,但如果你做足够的努力,C ++将允许它。

Sure, you cannot directly/easily call private methods outside the class, but if you are making enough efforts, C++ will allow it.

这篇关于能够使用指针来调用外部类的私有方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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