加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 能够使用指向函数的指针来调用外部类的私有方法

发布时间:2020-12-16 02:59:09 所属栏目:百科 来源:网络整理
导读:基于以下 answer到最近的 question,我可以使用一个函数指针,以便从另一个类Bar调用私有方法Foo T :: foo(),如下所示(另见 ideone) #include iostreamtemplatetypename Tstruct Bar{ typedef void (T::*F)(); Bar( T t_,F f ) : t( t_ ),func( f ) { } void o
基于以下 answer到最近的 question,我可以使用一个函数指针,以便从另一个类Bar调用私有方法Foo< T> :: foo(),如下所示(另见 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.是否有效?

解决方法

是的,这是允许的,它是有效的.

C++ Programming by Bjarne Stroustoup

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

当然,你不能直接/轻松地调用课外的私人方法,但是如果你付出了很多努力,C就会允许它.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读