使用std::vector和类对象时出错

Error when using std::vector and class objects

本文关键字:对象 出错 std vector 使用      更新时间:2023-10-16

这是错误"没有重载函数的实例…"。当我试图传递多个参数时,会得到它。当我从文件中删除除一个以外的所有文件时,它工作得很好。

这是我得到错误的ObjectHandler.cpp。

    #include <SFMLGraphics.hpp>
    #include <memory>
    #include "ObjectHandler.hpp"
    #include "Platform.hpp"
    #include "Game.hpp"
    ObjectHandler::ObjectHandler()
    {
    platforms_.push_back(sf::Vector2f(0, 680), sf::Vector2f(40, 2000)
, sf::Color(100, 255, 40)); //This is the line where I get the error.
}
void ObjectHandler::render(sf::RenderWindow& window)
{
    for (auto platform : platforms_)
        platform.render(window);
}

这是班级的hpp。

#ifndef PLATFORM_HPP
#define PLATFORM_HPP
#include <SFMLGraphics.hpp>
class Platform
{
public:
    Platform(sf::Vector2f position, sf::Vector2f size, sf::Color color);
    void render(sf::RenderWindow& window);
    sf::Vector2f getPosition() const;
    sf::FloatRect getBounds() const;
private:
    sf::RectangleShape platform_;
    sf::Vector2f position_;
};
#endif

这是cpp文件。

#include <SFMLGraphics.hpp>
#include "Platform.hpp"
Platform::Platform(sf::Vector2f position, sf::Vector2f size, sf::Color color)
    : position_(position)
{
    platform_.setPosition(position);
    platform_.setFillColor(color);
    platform_.setSize(size);
}
sf::FloatRect Platform::getBounds() const
{
    return platform_.getGlobalBounds();
}
sf::Vector2f Platform::getPosition() const
{
    return position_;
}
void Platform::render(sf::RenderWindow& window)
{
    window.draw(platform_);
}

我不明白为什么会发生这种事。。。我曾试图通过搜索谷歌来获得答案,但没有成功。我真的很感激任何帮助!:)

您需要构建一个实际的平台,此时您正试图将一堆Vector2fColor对象推送到platforms_向量中。

例如

platforms_.push_back(Platform(sf::Vector2f(0, 680),
    sf::Vector2f(40, 2000), sf::Color(100, 255, 40)));

以下操作也应该有效,编译器将从初始值设定项列表中推导类型,并在最后调用与上例中相同的构造函数。

platforms_.push_back({sf::Vector2f(0, 680),
    sf::Vector2f(40, 2000), sf::Color(100, 255, 40)});

然而,为了避免不必要的复制,你应该把它放在矢量上,而不是推送它

platforms_.emplace_back(sf::Vector2f(0, 680),
    sf::Vector2f(40, 2000) , sf::Color(100, 255, 40));

这样做的目的是在向量上的适当位置构建对象,有关template_back的更多信息,请参阅cppreference。

我认为是

platforms_.push_back(Platform(sf::Vector2f(0, 680), sf::Vector2f(40, 2000) , sf::Color(100, 255, 40)));

而不是

platforms_.push_back(sf::Vector2f(0, 680), sf::Vector2f(40, 2000) , sf::Color(100, 255, 40));