【问题标题】:C++ void type - how?C++ void 类型 - 如何?
【发布时间】:2010-07-15 15:15:49
【问题描述】:
typedef void(Object Sender) TNotifyEvent;

这就是我试图从 Delphi 到 C++ 做的事情,但它无法使用 'type int unexpected' 进行编译。

结果应该是我可以这样使用的东西:

void abcd(Object Sender){
  //some code
}

void main{
   TNotifyEvent ne = abcd;
}

如何使这种类型(类型为 void)?我对 C++ 不是很熟悉。

【问题讨论】:

  • void main() 不是标准 C++。 main() 总是返回 int
  • 您是否尝试切换到 C++Builder(并使用与 Delphi 相同的 TObject 和 TNotifyEvent 类型),或者您是否尝试使用类似于 Delphi 的设计在直接 C++ 中设置事件处理程序?
  • 正在尝试从 Delphi 到 VC++ 实现 TTimer 类。

标签: c++ types void


【解决方案1】:

你想要一个指向一个函数的指针吗?该函数接受一个对象但什么都不返回?

 typedef void (*TNotifyEvent)(Object Sender);

【讨论】:

    【解决方案2】:

    如果你想要定义一个函数的类型,它接受一个对象作为参数并且什么都不返回,那么语法应该是:

    typedef void TNotifyEvent( Object Sender );
    

    编辑,作为对评论的回答。

    是的,你可以定义一个函数的类型,这个类型以后可以用在不同的上下文中,具有不同的含义:

    TNotifyEvent func;          // function declaration (weird as it might look)
                                // same as: void func( Object Sender );
    TNotifyEvent *fp = func;    // function pointer declaration -- initialized with &func
    void func( Object Sender )  // cannot use the type when defining the function
    {}
    void foo( TNotifyEvent f ); // compiler translates to TNotifyEvent * f
                                // just as 'int a[5]' is converted to 'int *a' 
                                // in function parameter lists.
    

    【讨论】:

    • 嗯...可以用吗? C++ 不能有一个函数类型,只是一个指向函数的指针,对吧?
    • 我想知道这个问题的问题是什么——因此是反对票。 @James Curran,是的,你可以。
    • 其实可以的。 C++中有函数类型,只是没有函数类型的变量。但是例如。您作为 std::function 的参数输入的实际上是函数类型。见这里:ideone.com/fsn3O 和这里ideone.com/s8oY9
    【解决方案3】:

    不,因为 C++ 中没有通用的“对象”类。您可能想要的是一个回调(查看事件...),您需要一个函子(一个重载operator() 的类)或一个函数指针。

    下面是一个使用函数指针的例子:

    typedef void (*TNotifyEvent)(void *sender);
    

    【讨论】:

    • 您可以定义一个 Object 类,并让您的其他类继承它。这不是惯用的 C++,但你可以做到。当然,它不会涵盖任何系统定义的或外部的类。
    猜你喜欢
    • 2019-05-26
    • 2023-03-16
    • 2017-02-28
    • 2016-12-27
    • 2011-04-08
    • 2014-06-29
    • 1970-01-01
    • 2016-06-29
    • 1970-01-01
    相关资源
    最近更新 更多