【问题标题】:Accessing classes from another source in C++, issues initializing the constructor在 C++ 中从另一个源访问类,初始化构造函数时出现问题
【发布时间】:2013-01-25 10:03:33
【问题描述】:

我有一个名为 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

【问题讨论】:

  • 20player.h 行是什么?因为看起来你已经先在那里实现了它。
  • 空行?奇怪
  • 您的main.cpp 是什么样的?我怀疑你可能有#include "player.cpp" 而不是#include "player.h"
  • 我在顶部有 #include "player.h" 然后我调用 "Player p(0, 0, 0, 0, 0);"在课堂上也是如此。当我注释掉对象声明时,它运行得很好。虽然有点反直觉..

标签: c++ class constructor header


【解决方案1】:

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

您将您的player.h 包含在main.cpp 中,它在那里获得了该编译单元的一个定义。 然后它被包含在player.cpp 中,在那里它得到了第二个定义。

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

#ifndef PLAYER_H
#define PLAYER_H

// all your class definition code here

#endif

【讨论】:

  • #pragma once 虽好,但不符合标准。请在答案中使用兼容的 C++。
  • @KonradRudolph 确实应该如此。毕竟,我们正处于二十一世纪。
  • @Bartek 这不是重点。我希望在 C++ 标准中有很多东西。
  • @KonradRudolph 你是对的,我添加了经典方法。
  • 最大的 bug 是在椅子和屏幕之间 :-)。随着时间的推移,你会学到这一点:-)。祝你好运!
猜你喜欢
  • 2023-02-02
  • 1970-01-01
  • 2013-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多