c++ - 构造函数的重新定义

标签 c++ constructor

我昨天才刚刚开始学习 C++,所以我是全新的,尽管我是从 Java 过来的。 我正在制作游戏作为我的第一个小项目。 我想让我的播放器类与主文件分开。 我的头文件和 cpp 文件组成如下:

标题:

#pragma once

#include <SFML/Graphics.hpp>
#include <iostream>

class Entity {
    public:
        Entity(int x, int y, sf::RenderWindow& win) : window(win) {}
        void tick();
        void render();
    private:
        int x;
        int y;
        float velX;
        float velY;
        sf::RenderWindow& window;
        bool keys[264] = {};
};

C++:

#include <SFML/Graphics.hpp>
#include <iostream>

#include "headers/Entity.h"

using namespace sf;

Texture texture;
Sprite sprite;

Entity::Entity(int x, int y, RenderWindow& win) : window(win) {
    this->x = x;
    this->y = y;
    this->velX = 0;
    this->velY = 0;
    this->window = win;


    texture.loadFromFile("../res/img/test.png");
    sprite(texture);
}

void Entity::tick() {

    // movement
}

void Entity::render() {
    this->window.draw(sprite);
}

但是在 cpp 文件中,构造函数一直在说:

redefinition of 'Entity::Entity(int, int, sf::RenderWindow&)'

我已经搜索了很多次如何解决这个问题,但我找不到任何有效的方法,因为无论我尝试什么,这个问题都会继续存在。我更喜欢这个理论,因为我对任何答案都是全新的。 谢谢。

最佳答案

您的 header 提供构造函数的实现/定义:

    Entity(int x, int y, sf::RenderWindow& win) : window(win) {}

您的源文件也是如此。

将 header 更改为仅包含声明:

    Entity(int x, int y, sf::RenderWindow& win);

关于c++ - 构造函数的重新定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60902857/

相关文章:

c++ - 无法调整缓冲区以适应数据

c++ - 没有匹配函数调用 'WidgetBridge::WidgetBridge()'

c# - .NET 构造函数和内存管理问题

c++ - 继承中调用构造函数/析构函数的顺序

c++ - Boost 序列化在 32 位和 64 位机器之间不起作用。任何其他序列化/压缩库?

c++ - 如何专门针对 2 个不同值的模板?

c++ - 抛出一个 boost::shared_ptr< customException>

c++ - 在用 C\C++ 编写的代码上下文中的乱序执行与有序执行

具有新实例参数的 C++ 11 委托(delegate)构造函数?

c++ - 当其键不存在时初始化 std::map 值