我昨天才刚刚开始学习 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/