【问题标题】:Class type scope类类型范围
【发布时间】:2011-12-04 16:09:53
【问题描述】:

我在 Xcode 中有一个 Objective-C++ 项目,它在正常构建方案下编译得很好,但是当我为存档、分析或配置文件编译时,我得到了编译错误:

在此范围内必须使用“类”标签来引用类型“线”

这是我的代码的一个非常简化的版本:

class Document;

class Line
{
public:
    Line();

private:
    friend class Document;
};

class Document
{
public:
    Document();

private:
    friend class Line;
};

错误发生在我尝试使用 Line 类型的任何地方。例如。

Line *l = new Line();

您知道如何修复此错误消息以及为什么它仅在以上述方案之一进行编译时出现?

【问题讨论】:

  • "编译实现Document方法的document.mm文件时出错。"然而你决定我们不需要看到它。
  • 实现文件中是否包含类定义?
  • 是的。好像知道是什么类型,只是因为某种原因想让我每次都在它前面声明class。

标签: c++


【解决方案1】:

我的代码中有这个问题。查看生成的预处理文件后,我发现我的一个类名与函数名相同。所以编译器试图通过要求在类型前面添加类标签来解决歧义。

代码前(有错误):

template <typename V>
void Transform(V &slf, const Transform &transform){ // No problem
//... stuff here ...
}

void Transform(V2 &slf, const Transform &transform); // Error: Asking to fix this

void Transform(V2 &slf, const class Transform &transform); // Fine

//Calling like
Transform(global_rect, transform_);

代码后:

template <typename V>
void ApplyTransform(V &slf, const Transform &transform){ // No problem
//... stuff here ...
}

void ApplyTransform(V2 &slf, const Transform &transform);

//Calling like
ApplyTransform(global_rect, transform_);

【讨论】:

  • 将结构/类成员命名为与结构/类名称相同时会出现同样的问题。我在 thrift 文件中犯了这个错误,生成的文件有编译错误。
  • 如果你在枚举中有一个类名。
【解决方案2】:

这并不能回答您的问题,但鉴于所提供的信息无法回答,我将提出此建议。与其让Document 成为朋友,或者让LineLine 成为Document 的朋友,不如让Document 包含对我来说更有意义并且看起来更好封装的行。

class Line
{
public:
    Line();
};

class Document
{
public:
    Document();

private:
    std::vector<Line> m_lines;
};

【讨论】:

    【解决方案3】:

    我设法通过将“Line”类型名称重构为其他名称来解决此问题。我能想到的唯一解释是,在执行和归档构建时,Xcode 在一些外部源中编译,它定义了另一种“线”类型。因此,它需要“类”说明符来阐明类型。

    【讨论】:

      猜你喜欢
      • 2010-12-14
      • 2018-06-25
      • 1970-01-01
      • 2012-10-30
      • 2012-04-17
      • 2013-06-15
      • 2019-03-17
      • 1970-01-01
      • 2019-07-06
      相关资源
      最近更新 更多