Accessing classes from another source in C++, issu

2019-05-10 21:11发布

问题:

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

回答1:

You probably haven't protected your .h file.

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.

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