c中的冲突声明

新手上路,请多包涵

我有一个cpp文件如下:

 #include <iostream>

#include "i.h"

using namespace std;

typedef struct abc{
int a1;
int b1;
} abc_t, *abc;

void fun(abc x){
cout<<x->a1;
}

int main(){
abc val;
fun(val);
return 0;
}

ih 文件:

 struct abc;

void fff(struct abc);

当我编译代码时发生以下错误:

 t.cpp:8: error: conflicting declaration ‘typedef struct abc* abc’

t.cpp:5: error: ‘struct abc’ has a previous declaration as ‘struct abc’

t.cpp: In function ‘void fun(abc)’:

t.cpp:11: error: base operand of ‘->’ has non-pointer type ‘abc’

如果我将 cpp 文件保存为 c 文件并使用 c 编译器进行编译,那么一切正常。 c++编译器有什么问题?

原文由 Karthik K M 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.4k
2 个回答

在 C 中,这是:

 struct abc
{
   int a1;
   int b1;
};

创建一个类型 struct abc (粗略地说),但不是一个类型 abc

这就是为什么您使用 typedef 技巧来创建我们可以使用的类型,而无需在任何地方编写 struct

 typedef struct abc{
   int a1;
   int b1;
} abc_t;

现在您也有了 abc_t 类型,它与 struct abc 相同。仍然没有类型 abc

因此,当您添加一个名为 abc 的指针的声明时,这是有效的,因为尚未使用该名称。


在 C++ 中,原始声明创建了一个名为 abc 的类型。不需要 typedef 技巧,并且您声明的指针 abc 是无效的,因为名称 abc 被占用。


解决方案

您可以像这样消除您的姓名的歧义(并对代码进行去混淆处理):

 struct abc
{
   int a1;
   int b1;
};
typedef struct abc abc_t;
abc_t* ptr_to_abc;

或者,如果您正在编写 C++ 并且不需要 C 兼容,则只需:

 struct abc
{
   int a1;
   int b1;
};

abc* ptr_to_abc;

原文由 Lightness Races in Orbit 发布,翻译遵循 CC BY-SA 4.0 许可协议

您已使用 typedefabc 声明为结构和指向结构的指针。这和这样做是一样的:

 struct abc {...};
typedef abc abc_t; // ok, abc_t is now an alias for abc
typedef abc *abc;  // error

Skip the typedef , abc_t and *abc and use the class (with all members public per default) abc as-is.

struct abc {
    int a1 = 0;
    int b1 = 0;
};

void fun(const abc& x);

i.cpp

 #include <iostream>
#include "i.h"

void fun(const abc& x) {
    std::cout << x.a1 << "\n";
}

主文件

#include <iostream>
#include "i.h"

int main(){
    abc val;
    fun(val);
    return 0;
}

原文由 Ted Lyngmo 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题