我有一个名为 Player 的类,它有一个构造函数,它采用在我的“player.h”文件中声明的 5 个浮点参数,然后在我的“player.cpp”文件中初始化,如帖子底部所示。
每当我尝试运行该程序时,我都会收到错误消息:
build/Debug/MinGW-Windows/player.o: In function `Player':
C:\Users\User\Dropbox\NetBeans Workspace\Testing/player.cpp:11: multiple definition of `Player::Player(float, float, float, float, float)'
build/Debug/MinGW-Windows/main.o:C:\Users\User\Dropbox\NetBeans Workspace\Testing/player.h:20: first defined here
我在这里做错了什么?我试图在构造函数之前去掉“public:”,但这根本没有帮助。它说我有多个构造函数定义,但我只初始化了一次。我相信这是显而易见的。
两个文件的完整来源:
“播放器.cpp”
#include "player.h"
Player::Player(float x, float y, float z, float rx, float ry) {
}
“播放器.h”
#ifndef PLAYER_H
#define PLAYER_H
class Player {
public:
Player(float x, float y, float z, float rx, float ry);
};
#endif
最佳答案
您可能没有保护您的 .h
文件。
您将您的player.h
包含在main.cpp
中,在那里它获得了该编译单元的一个定义。
然后它被包含在 player.cpp
中,在那里它获得了第二个定义。
如果您的编译器不支持#pragma once
,您将不得不使用经典 手动保护它们:
#ifndef PLAYER_H
#define PLAYER_H
// all your class definition code here
#endif
关于c++ - 从 C++ 中的另一个源访问类,初始化构造函数时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14792903/