c++ 错误:“Function”不是“Class”的非静态数据成员或基类

vybvopom  于 2023-03-05  发布在  其他
关注(0)|答案(3)|浏览(148)

我在代码中实现了Component类,并且运行良好

namespace GUI {
  class Component: public sf::Drawable, public sf::Transformable, private sf::NonCopyable {
    public:
    //Variables
  };
}

我正在学习的书也要求我在GUI名称空间中实现另一个名为Container的类

Container::Container(): mChildren(), mSelectedChild(-1) {
    
}

void Container::pack(Component::Ptr component) {
  mChildren.push_back(component);
  if (!hasSelection() && component -> isSelectable())
    select(mChildren.size() - 1);
}

bool Container::isSelectable() const {
  return false;
}

我不明白的是他实现类的方式,这给了我帖子标题中的语法错误:

Error: mChildren is not a Nonstatic data member or a base class of class GUI::Container.

我试了进一步的代码:

class Container {
  Container::Container(): mChildren(), mSelectedChild(-1) {}
  void Container::pack(Component::Ptr component) {
    mChildren.push_back(component);
    if (!hasSelection() && component -> isSelectable())
      select(mChildren.size() - 1);
  }
  
  bool Container::isSelectable() const {
    return false;
  }
};

但是我还是会遇到语法错误,到底是什么错误,我应该读些什么?

  • 注:我也读过C++指南书籍,但我没有找到答案,因为我可能不知道如何参考这个问题。*
ssm49v7z

ssm49v7z1#

当您在class声明中定义方法时,您不能使用:: scope resolution operator
你的方法也应该是公共的,最后你必须确定你的mChildren成员定义正确。

class Container
{
    // ...

public:
    Container()
//  ^^
       : mChildren()
       , mSelectedChild(-1)
    {
    }
    void pack(Component::Ptr component)
//       ^^
    {
         // ...
    }
    bool isSelectable() const
//       ^^
    {
        // ...
    }

private:
    std::vector<Component::Ptr> mChildren;   // Example of a definition of mChildren
    //          ^^^^^^^^^^^^^^ replace with the good type

};
yvt65v4c

yvt65v4c2#

在这段代码中,你使用了mChildren,但是它没有在你的Container类中定义。mChildren应该是什么?
如果它是Component::Ptr的向量,则需要在类中定义它。

std::vector<Component::Ptr>mChildren;
e0bqpujr

e0bqpujr3#

为什么你要在构造函数初始化列表中初始化mChildren?更具体地说,这个调用mChildren()在做什么?试着删除那个调用,看看会发生什么。

相关问题