Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/image/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用g+编译时出现不完整的类型错误+;_C++_Scope_Union_Declaration_Qualified Name - Fatal编程技术网

C++ 使用g+编译时出现不完整的类型错误+;

C++ 使用g+编译时出现不完整的类型错误+;,c++,scope,union,declaration,qualified-name,C++,Scope,Union,Declaration,Qualified Name,我试图使用g++执行以下代码,但得到了不完整的类型错误 #include <stdio.h> struct try_main{ union{ struct try_inner_one{ int fl; float g; }one; struct try_inner_two{ char a; }two; }un; int chk; }; void func(struct try_inner_one o){

我试图使用g++执行以下代码,但得到了不完整的类型错误

#include <stdio.h>
struct try_main{
  union{
    struct try_inner_one{
      int fl;
      float g;
    }one;
    struct try_inner_two{
      char a;
    }two;
  }un;
  int chk;
};

void func(struct try_inner_one o){
  printf("%d\n",o.fl);
}
int main(){
  struct try_main z = {{1,2},3};
  func(z.un.one);
return 0; 
}
以上代码已使用gcc成功编译

此错误的原因是什么?如何修复此错误


谢谢

C和C++有不同的范围规则。C++中的类型的全称不是<代码>结构> TyyInNyOne < /C>,因为类型定义嵌套在代码“> TyyMyth中的未命名联合内。1</P>

如果您想编写在C和C++中都相等工作的代码,请将类型定义拉到顶层:

struct try_inner_one {
  int fl;
  float g;
};

struct try_inner_two {
  char a;
};

struct try_main {
  union {
    struct try_inner_one one;
    struct try_inner_two two;
  } un;
  int chk;
};

1,此类型的完全限定名不能在C++中拼写,因为嵌套的类型是未命名的。您可以给联合类型命名,这样就可以在C++中拼写<代码> > TyyInNyOne <代码>的完全限定名。但是,该名称不是合法的C代码,因为C没有范围解析操作符

如果要保留嵌套类型定义,可以为该联合指定一个名称(在下面的,
union\u name
中),并执行以下操作以保持代码同时为C和C++编译:

// (Type definition omitted.)

#ifdef __cplusplus
using try_inner_one = try_main::union_name::try_inner_one;
#else
typedef struct try_inner_one try_inner_one;
#endif

void func(try_inner_one o){
  printf("%d\n", o.fl);
}
这个错误的原因是什么

<>原因是代码>嵌套在“代码> > TyyMyth</代码>中的联合内嵌套的代码:TyyIn NyLoNo.<代码>不能在C++中的该联盟外部的上下文中查找不合格名称(与C不同)。 如何解决这个问题

可以在C++中使用限定名称:

void func(decltype(try_main::un)::try_inner_one o){
如果您为工会命名,则可以简化:

union u { // note the name
    struct try_inner_one{

void func(try_main::u::try_inner_one o){
跨语言兼容的解决方案是按照Kondrad Rudolph的回答中所述,在彼此之外定义结构



<>一个警告词:C++对C++中的非活动成员如何访问比C更具限制性。

< P>看来,你正在编译程序作为C++程序。在这种情况下,结构
try\u main
中的每个声明都具有此结构的范围

所以你需要像这样声明函数

void func( decltype( try_main::un )::try_inner_one o );


你在寻找正确的C和C++吗?或者只是让它在C++中工作就好了?我正在寻找正确的C++工作方式,为什么错误不来,因为这个错误是因为你编写了一个C程序,但是试图把它编译成C++。C和C++是两种完全不同的语言。
void func( decltype( try_main::un )::try_inner_one o );
void func( const decltype( try_main::un )::try_inner_one &o );