在C++中从另一个源访问类,会初始化构造函数

Cod*_*ler 3 c++ constructor header class

我有一个名为Player的类,它有一个构造函数,它在我的"player.h"文件中声明了5个float参数,然后在我的"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
Run Code Online (Sandbox Code Playgroud)

我在这做错了什么?我尝试在构造函数之前删除"public:",但这根本没有帮助.它说我有多个构造函数的定义,但我只初始化一次.我确信这是显而易见的.

这两个文件的完整来源:

"player.cpp"

#include "player.h"

Player::Player(float x, float y, float z, float rx, float ry) {

}
Run Code Online (Sandbox Code Playgroud)

"player.h"

#ifndef PLAYER_H
#define PLAYER_H

class Player {

public:

    Player(float x, float y, float z, float rx, float ry);
};

#endif
Run Code Online (Sandbox Code Playgroud)

Ste*_*and 5

您可能没有保护您的.h文件.

你包括你的player.hin main.cpp,它有一个这个编译单元的定义.然后它被包含在内player.cpp,它获得了第二个定义.

如果您的编译器不支持#pragma once,您将不得不使用经典的手动保护它们:

#ifndef PLAYER_H
#define PLAYER_H

// all your class definition code here

#endif
Run Code Online (Sandbox Code Playgroud)

  • `#pragma once`,虽然它很好,但不符合标准.请在答案中使用兼容的C++. (3认同)
  • 最大的错误是在椅子和屏幕之间:-).你会随着时间的推移了解到:-).祝好运 ! (2认同)