gpt4 book ai didi

c++ - 使用两个相同的 typedef 不好吗?如何避免?

转载 作者:搜寻专家 更新时间:2023-10-31 00:01:56 25 4
gpt4 key购买 nike

由于循环依赖,您对某些类使用前向声明:

//B.h
class A;
class B
{
public:
void foo(A* a);
};
typedef SmartPtr<B> BPtr;

//A.h
class B;
class A
{
public:
void foo(B* b);
};
typedef SmartPtr<A> APtr;

现在,假设我想更改函数的原型(prototype)以使用智能指针:

void A::foo(BPtr b);
void B::foo(APtr a);

显然,我不能转发声明APtrBPtr。有效的方法是重新使用 typedef:

//B.h
class A;
typedef SmartPtr<A> APtr;
class B
{
public:
void foo(APtr a);
};
typedef SmartPtr<A> APtr;

//A.h
class B;
typedef SmartPtr<B> BPtr;
class A
{
public:
void foo(BPtr b);
};
typedef SmartPtr<A> APtr;

但我不确定这是否是正确的解决方案。有这样做的标准方法吗?我的做法是错误的还是危险的?

最佳答案

假设您对这些循环依赖有充分的理由,为什么不这样做:

// defs.h
class A;
class B;
typedef SmartPtr<A> APtr;
typedef SmartPtr<B> BPtr;

//B.h
#include "defs.h"
class B
{
public:
void foo(APtr a);
};

//A.h
#include "defs.h"
class A
{
public:
void foo(BPtr b);
};

关于c++ - 使用两个相同的 typedef 不好吗?如何避免?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9033502/

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