【问题标题】:Return a Struct defined in a separate header file: unknown type name返回在单独的头文件中定义的结构:未知类型名称
【发布时间】:2014-12-11 16:45:45
【问题描述】:

您好,我正在使用 C++(具体来说是 Tizen 平台)做一个项目,我对这个项目很陌生。如何实现返回结构的函数,该结构在单独的头文件中定义?我以为你会像下面的代码那样去做。

文件名.h

1.  typedef struct StructName {
2.      int hello;
3.      int there;
4.      int friend;
5.      Foo(int num) : hello(99), there(25) {
6.          friend = num;
7.      }
8.  } StructName;
9.
10. virtual StructName FunctionName(void);

第 10 行的返回类型 StructName 上的函数前向声明似乎正确引用了 FileName.h 文件中的结构。

文件名.cpp

1.  #include FileName.h
2.
3.  StructName FunctionName(void) {
4.      int n = 5;
5.      StructName s(n);
6.      return s;
7.  }

我收到的错误是 FileName.cpp 中的第 3 行上的“未知类型名称 'StructName'”。
但是,第 5 行 FileName.cpp 中的 StructName 似乎正确地引用了头文件中的结构。

我一直在尝试阅读 Stack Overflow 上的类似问题,但没有一个答案能解决我的问题。

例如,
如果我在函数的返回类型(在两个文件中)和 FileName.cpp 函数中的返回变量 s 前面添加关键字“struct”,我会收到另一个错误消息:

  • 'FileName::FunctionName' 的行外定义与返回类型中的声明不同


  • 没有从“struct StructName”(又名“FileName::StructName”)到“struct StructName”(又名“StructName”)的可行转换

【问题讨论】:

  • 附带说明,您不应将变量命名为 friend,因为它是 C++ 关键字。
  • 请显示您的班级背景。错误消息中的 virtual 关键字和 FileName::FunctionName 不符合您的全局定义。
  • @Cyber​​ 感谢您指出这一点。我不知道。无论如何,我的朋友帮助我解决了这个问题,我将在下面发布解决方案。
  • @aschelper 这可能与 Tizen 有关,因为它确实是我收到的错误消息。如果我从 FileName.h 中的函数声明中删除了 virtual 关键字,则错误消息没有区别。

标签: c++ struct tizen


【解决方案1】:

对我有用的解决方案可能与 Tizen 相关,因为我之前在 Stack Overflow 上没有看到任何关于此解决方案的帖子(而且 Tizen 并不常见)。如果有人可以确认或否认,那就太好了。

无论如何,我朋友想出的解决方案是在FileName.cpp中指定的函数的返回类型前面添加'FileName::'(在FileName.h中不需要)完整的解决方案在下面发布解决问题的要点(FileName.cpp 中的第 3 行)。

文件名.h

1.  typedef struct StructName {
2.      int hello;
3.      int there;
4.      int friend;
5.      Foo(int num) : hello(99), there(25) {
6.          friend = num;
7.      }
8.  } StructName;
9.
10. virtual StructName FunctionName(void);

文件名.cpp

1.  #include FileName.h
2.
3.  FileName::StructName FunctionName(void) { // <- Adding 'FileName::' infront of
4.      int n = 5;                            // the return type fixed the problem
5.      StructName s(n);
6.      return s;
7.  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多