在C ++中从另一个源访问类,会初始化构造函数 [英] Accessing classes from another source in C++, issues initializing the constructor

查看:116
本文介绍了在C ++中从另一个源访问类,会初始化构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为Player的类,它有一个构造函数,它在我的player.h文件中声明了5个float参数,然后在我的player.cpp文件中初始化,如帖子底部所示。

I have a class called Player that has a constructor that takes 5 float parameters declared in my "player.h" file and then initialized in my "player.cpp" file as shown at the bottom of the post.

每当我尝试运行程序时,都会出现错误:

Whenever I try to run the program, I get the error:

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

我在这里做错了什么?我试图摆脱公共:之前的构造函数,但这没有帮助。它说我有多个定义的构造函数,但我只初始化它一次。我相信这是明显的事情。

What am I doing wrong here? I tried getting rid of the "public:" before the constructor, but that didn't help at all. It says I have multiple definitions of the constructor, but I only initialize it once. I am sure it is something obvious.

这两个文件的完整源代码:

The complete source of the two files:

player.cpp

#include "player.h"

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

}

player.h

#ifndef PLAYER_H
#define PLAYER_H

class Player {

public:

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

#endif


推荐答案

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

You probably haven't protected your .h file.

您包括您的 player.h c> 中,它为此编译单元获取一个定义。
然后它包含在 player.cpp 中,它获得第二个定义。

You include your player.h in main.cpp, there it gets one definition for this compilation unit. And then it's included in player.cpp, where it gets a second definition.

编译器不支持 #pragma once ,您必须使用古典手动保护它们:

If your compiler doesn't support #pragma once, you'll have to manually protect them with the classical :

#ifndef PLAYER_H
#define PLAYER_H

// all your class definition code here

#endif

这篇关于在C ++中从另一个源访问类,会初始化构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆