C++ 指向函数的友元指针

标签 c++ windows-8.1 c++-cx

我有一个引用类:

public ref class class1 sealed
{
    bool (*pointer_to_function)(args);
}
bool function1(args);
//inside of class1 functions
pointer_to_function = &function1;

如何传递给 function1class1 的引用以访问 class1 中的所有数据(包括私有(private)数据)? 如果 args == "class1^ args"function1 就会充满错误。 此外,我无法将 pointer_to_function 设置为类的友元。

最佳答案

  bool (*pointer_to_function)(args);

那是一个C函数指针声明。请记住,您的“class1”可以由不了解 C 的 bean 的代码使用。例如 Javascript 或 VB.NET。所以这是不可能的,编译器会提示,您必须改用委托(delegate)。委托(delegate)是 C++/CX 提供的语法糖,用于声明可以跨多种语言工作的函数指针。它们比 C 函数指针更强大,它们还可以调用类的实例方法。

一个简单的例子:

namespace Foo {
    public delegate void mycallback(int arg);

    public ref class class1 sealed {
    public:
        property mycallback^ pointer_to_function;
    };
}

如果你想用 C++ 代码初始化它,那么你应该这样写:

ref class Bar {
private:
    Foo::class1^ obj;
    void callbackFunction(int arg) { }
public:
    Bar() : obj(ref new Foo::class1) {
        obj->pointer_to_function = ref new Foo::mycallback(this, &Bar::callbackFunction);
    }
};

请保留 event keyword记在心里。

关于C++ 指向函数的友元指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27607399/

相关文章:

c++将自动矩阵传递给函数

c++ - Combox第一行不可选择

c++ - OpenGL对象创建

C++,使用 Ctrl+C 携带存储语句的缓冲区

c++ - C/C++ : Packing or padding data in a struct

c# - 如何使用 SharpDX 调用 Trim?

c++ - 使用英特尔 C++ 编译器 2015 Windows 构建 Boost 1.56

node.js - 无法在 WIndows 中使用 npm

c++ - 如何在 Canvas 上画一个径向渐变的圆?

xaml - 数据绑定(bind)到 ComboBox c++/cx XAML Metro 应用程序时 SelectedValue、SelectedIndex 的问题