【发布时间】:2016-09-20 11:50:36
【问题描述】:
我在类定义中使用了“typedef”,但是当这个类出现在不同的位置时,它的执行方式不同,可能会导致错误。请帮我检查以下代码。
这个版本的代码可能会报错:
#include <vector>
#include <string>
class B;
class A
{
public:
A() { }
std::vector<B::size_type> vec;
};
class B
{
public:
typedef std::vector<std::string>::size_type size_type; // [Error] incomplete type 'B' used in nested name specifier
};
但以下代码运行正常:
#include <vector>
#include <string>
class B
{
public:
typedef std::vector<std::string>::size_type size_type;
};
class A
{
public:
A() { }
std::vector<B::size_type> vec;
};
【问题讨论】:
-
因为代码是按顺序解析的(从上到下)。在第一个版本中,B 仅是前向声明的,并且 typedef 是未知的。在第二个版本中,B 在使用 typedef 之前已经完成。
标签: c++11 typedef incomplete-type