c ++中的冲突声明

Kar*_*K M 0 c++ struct typedef

我有一个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;
}
Run Code Online (Sandbox Code Playgroud)

ih文件:

struct abc;

void fff(struct abc);
Run Code Online (Sandbox Code Playgroud)

当我编译代码时出现以下错误:

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’
Run Code Online (Sandbox Code Playgroud)

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

Ted*_*gmo 10

您已abc通过使用声明为结构和指向结构的指针typedef.它和做的一样:

struct abc {...};
typedef abc abc_t; // ok, abc_t is now an alias for abc
typedef abc *abc;  // error
Run Code Online (Sandbox Code Playgroud)

跳过typedef,abc_t然后*abcabc原样使用类(默认情况下公开所有成员).

IH

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

void fun(const abc& x);
Run Code Online (Sandbox Code Playgroud)

i.cpp

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

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

main.cpp中

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

int main(){
    abc val;
    fun(val);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)