【问题标题】:Compiler error while pushing a pointer to a forward declared type into a typedef'd vector将指向前向声明类型的指针推入 typedef 向量时出现编译器错误
【发布时间】:2017-02-21 11:55:59
【问题描述】:

所以我得到的错误是:

error: no matching function for call to 'std::vector<Type*>::push_back(AnimationAutoComplete::Type*&)'
 neighbours.push_back(samplePoint);
                                 ^

我制作了一个精简版项目来重现该错误。 这是我的AnimationAutoComplete.h

#include <vector>

class Type;
typedef std::vector<Type *> SetOfConstTQ;

class AnimationAutoComplete {
public:
  AnimationAutoComplete() {}
  ~AnimationAutoComplete() {}

  SetOfConstTQ getNeighbours();

  class Type
  {
  public:
      Type() {}
      const double point = 3.0;
  };
};

还有我的main.cpp

#include "AnimationAutoComplete.h"

SetOfConstTQ AnimationAutoComplete::getNeighbours()
{
    SetOfConstTQ neighbours;

    Type *samplePoint = new Type();

    neighbours.push_back(samplePoint);

    return neighbours;
}

int main()
{
    AnimationAutoComplete main;
}

【问题讨论】:

  • ::Type 不是::Whatever::Type

标签: c++ pointers vector reference


【解决方案1】:

cannot forward declare a nested class

AnimationAutoComplete 之外定义Type,您将修复您的程序:

#include <vector>

class Type;
typedef std::vector<Type *> SetOfConstTQ;

class AnimationAutoComplete { ... };

class Type { ... };
...

或者,typedef SetOfConstTQAnimationAutoComplete::Type 之后被完全定义:

#include <vector>

struct AnimationAutoComplete {
    struct Type {};
    typedef std::vector<Type*> SetOfConstTQ;
    SetOfConstTQ getNeighbours();
};

AnimationAutoComplete::SetOfConstTQ AnimationAutoComplete::getNeighbours()
{
    SetOfConstTQ neighbours;
    neighbours.push_back(new AnimationAutoComplete::Type());
    return neighbours;
}

int main()
{
    AnimationAutoComplete main;
    (void) main.getNeighbours();
}

live on coliru

【讨论】:

  • 您应该提到将声明 inside 移动到外部类也是一个有效的解决方案。
  • @MaximilianKöstler 我刚刚做到了;)
【解决方案2】:

您不能以这种方式转发声明。 AnimationAutoComplete::TypeType 不同。

【讨论】:

    【解决方案3】:

    如前所述,您不能前向声明嵌套类。

    但如果你想让你的类嵌套母鸡,你可以在类中 typedef 并稍后使用:

    class AnimationAutoComplete {
    public:
      AnimationAutoComplete() {}
      ~AnimationAutoComplete() {}
    
      class Type
      {
      public:
          Type() {}
          const double point = 3.0;
      };
    
      typedef std::vector<Type *> SetOfConstTQ; // Typedef here
      SetOfConstTQ getNeighbours(); // use it after typedef
    };
    
    AnimationAutoComplete::SetOfConstTQ AnimationAutoComplete::getNeighbours() // return type will come under scope of AnimationAutoComplete
    {
        SetOfConstTQ neighbours;
    
        Type *samplePoint = new Type();
    
        neighbours.push_back(samplePoint);
    
        return neighbours;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-03
      • 1970-01-01
      • 1970-01-01
      • 2021-10-14
      • 1970-01-01
      相关资源
      最近更新 更多