C++ 使用另一个类的 typedef'ed 成员时出现编译错误
C++ Compilation error when using typedef'ed members of another class
以下代码有什么问题。我收到编译错误。我也尝试过B类的前向声明。但未能成功。
测试.cpp
#include <memory>
#include <iostream>
namespace api
{
class A
{
public:
typedef std::shared_ptr<A> APtr;
APtr get_a_ptr();
B::BPtr get_b_ptr();
};
class B
{
public:
typedef std::shared_ptr<B> BPtr;
BPtr get_b_ptr();
A::APtr get_a_ptr();
};
}
int main(int argc, char **argv)
{
return 0;
}
这样做:
namespace api
{
class B; // forward declaration
class A
{
public:
typedef std::shared_ptr<A> APtr;
APtr get_a_ptr();
std::shared_ptr<B> get_b_ptr();
};
...
}
问题是您正在从类 B
请求尚未定义的内容。所以使用std::shared_ptr<B>
,你会没事的。
有关详细信息,请阅读:何时可以使用前向声明?
代码中的问题是 B::BPtr
没有在类 A 声明之前声明。您应该在使用前声明BPtr
。例如:
class B;
class A;
typedef std::shared_ptr<B> BPtr;
typedef std::shared_ptr<A> APtr;
class A
{
public:
APtr get_a_ptr();
BPtr get_b_ptr();
};
class B
{
public:
BPtr get_b_ptr();
APtr get_a_ptr();
};
请记住,在完整类声明之前,不能将operator*
和operator->
与shared_ptr
一起使用。
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 助记符和指向成员语法的指针
- 用于访问容器<T>数据成员的正确 API
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 嵌套在类中时无法设置成员数据
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 将函数类成员映射到类本身内部
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 将Ref对象作为类成员
- 将包含C样式数组的对象初始化为成员变量(C++)
- 如何将成员函数作为回调参数传递给需要"typedef-ed"自由函数指针的函数?
- 我应该移动 std::exchange ed 成员吗?
- C++ 使用另一个类的 typedef'ed 成员时出现编译错误
- 使用C++0x std::thread调用新ed对象中的成员函数