简体   繁体   English

将C转换为C ++:typdef生成错误

[英]Converting C to C++: typdef generating error

I need to convert a .c file into .cpp file and I came across this declaration: 我需要将.c文件转换为.cpp文件,我遇到了这个声明:

 typedef void handler_t(int);

 handler_t *Signal(int signum, handler_t *handler);

I included those two lines of code in the header file, and I add the actual function declaration function in the .cpp file. 我在头文件中包含了这两行代码,并在.cpp文件中添加了实际的函数声明函数。

 handler_t *Signal(int signum, handler_t *handler){ ...... } 

When I do this I get the error: "handler_t does not name a type".I have never worked before with typdef in C or C++, so can someone explain to me why I am getting an error? 当我这样做时,我得到错误:“handler_t没有命名类型”。我之前从未使用过C或C ++中的typdef,所以有人可以向我解释为什么我会收到错误吗?


My classes as requested: 我的课程要求:

 #ifndef A_H
 #define A_H

 class A
 {
     public:
       A();
       virtual ~A();

       typedef void handler_t(int);
       handler_t* Signal(int signum, handler_t *handler);

     protected:
     private:
 };

   #endif // A_H

///////////// /////////////

   #include "A.h"

   A::A()
   {
   }

   A::~A()
   {
   }

   handler_t* A::Signal(int signum, handler_t *handler) {

     ...........

    }

error: 错误:

    |694|error: ‘handler_t’ does not name a type|

Try changing it to: 尝试将其更改为:

typedef void (*handler_t)(int);

and: 和:

handler_t Signal(int signum, handler_t handler);

For reference check out signal() which does it like this: 作为参考,检查signal() ,它是这样的:

#include <signal.h>

typedef void (*sighandler_t)(int);

sighandler_t signal(int signum, sighandler_t handler);

Actually, looking at your new code, I think you have to do this: 实际上,看看你的新代码,我认为你必须这样做:

A::handler_t* A::Signal(int signum, A::handler_t *handler)

I think your new error "undefined reference to main" is unrelated to the question asked. 我认为您的新错误“未定义的主要参考”与提出的问题无关。 See this post for some ideas. 有关一些想法,请参阅此帖

handler_t* A::Signal(int signum, handler_t *handler) {

The problem is that the first mention of handler_t needs to be qualified with A:: . 问题是第一次提到handler_t需要用A::来限定。 Like this: 像这样:

A::handler_t* A::Signal(int signum, handler_t *handler) {

This is always the case when types defined inside a class are used as the return types of member functions. 当类中定义的类型用作成员函数的返回类型时,总是如此。 When you declare the function you're inside the class definition, so the nested typedef is known. 当您声明函数时,您在类定义中,因此嵌套的typedef是已知的。 And it's the same if you define the function inside the class definition. 如果在类定义中定义函数,它也是一样的。 But once you step outside the class definition you have to tell the compiler where handler_t is defined. 但是一旦你走出类定义,就必须告诉编译器在哪里定义了handler_t But the second mention of handler_t is okay, because at that point the compiler knows that it's compiling a member function of A , and it knows about the nested types in A . 但是第二次提到handler_t是可以的,因为在那时编译器知道它正在编译A的成员函数,并且它知道A的嵌套类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM