gpt4 book ai didi

C++:匿名结构的结构前向声明导致 "conflicting declaration"

转载 作者:行者123 更新时间:2023-12-05 03:16:12 32 4
gpt4 key购买 nike

我有这个 hpp 文件:

struct rte_spinlock_t;

class A {

public:
void init();
private:
rte_spinlock_t* spinlock;
};

和对应的cpp文件:

#include "A.hpp"

typedef struct {
int lock;
} rte_spinlock_t;

void A::init()
{

}


现在,像这样编译:g++ A.cpp 我得到这个错误:

A.cpp:5:3: error: conflicting declaration ‘typedef struct rte_spinlock_t rte_spinlock_t’
5 | } rte_spinlock_t;
| ^~~~~~~~~~~~~~
In file included from A.cpp:1:
A.hpp:2:8: note: previous declaration as ‘struct rte_spinlock_t’
2 | struct rte_spinlock_t;
| ^~~~~~~~~~~~~~

显然使命名为它的结构有效,不幸的是我无法控制库中 struct rte_spinlock_t 的类型定义。

我该如何解决这个问题?

我希望能够转发一个未命名的结构而不会陷入声明冲突。

最佳答案

据我了解,您所拥有的更多(错误代码): https://godbolt.org/z/zarsTq6oE

为什么不使用 pimpl(私有(private)实现)习惯用法来进行额外级别的间接访问并隐藏“血淋淋的细节”?

假设我的 X 是你的 Alib.h 包含麻烦的 typedef:

//example.cpp
#include "example.hpp"
#include "lib.h"

struct Impl
{
CStruct* cs;
};

void X::init()
{
clib_init(&impl->cs);
}

X::X()
{
impl = std::make_unique<Impl>();
}
X::~X() = default;
//example.hpp
#pragma once
#include <memory>

struct Impl;

struct X
{
X();
~X();

//rest of special functions omitted for brevity
//feel free to add them at your own leisure
void init();
std::unique_ptr<Impl> impl;

};

现场演示:https://godbolt.org/z/4jYGrYEjr

顺便说一句,我假设你的麻烦结构是基于一些搜索的 C 代码......

关于C++:匿名结构的结构前向声明导致 "conflicting declaration",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74784222/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com