For learning purpose i try following (text rpg context): I'm creating a Player object. Next i want to create a Monster object with passing the player object to that monster class. But i get a compilation error. I worked it out if I put everything in a single file. If i seperate my code into several header and source files i get the following compilation error:
1 2 3 4 5 6 7 8 9 10 11 12 13
$ g++ *.cpp
In file included from monster.cpp:1:0:
monster.h:7:17: error: expected ‘)’ before ‘&’ token
Monster(Player& x);
^
monster.h:9:3: error: ‘Player’ does not name a type
Player& p;
^
monster.cpp:3:17: error: expected constructor, destructor, or type conversion before ‘(’ token
Monster::Monster(Player& x)
^
monster.cpp:4:9: error: expected unqualified-id before ‘{’ token
: p{x} {
The code:
1 2 3 4 5 6 7 8
// main.cpp
#include "player.h"
#include "monster.h"
main () {
Player player1("Meanman");
Monster monster1(player1);
}
1 2 3 4 5 6 7 8 9 10 11 12
// player.h
#ifndef PLAYER_H
#define PLAYER_H
#include <string>
class Player {
public:
Player(std::string name);
private:
std::string playername;
};
#endif
//...
#define MONSTER_H
//The compiler needs to know that the identifier 'Player' refers to a type
//and not, say, a function.
class Player;
class Monster {
//...
Always compile with a high level of warnings - warnings are your friend, they tell you about things that will probably cause problems one way or another. Including things that will cause runtime errors.
If you don't have a C++14 compliant compiler (don't see why you can't), then substitute -std=c++11. ProgName is the name you want your executable file to have. IMO this is better than the default a.out
Actually if you can get hold of the latest version of g++ (6.1), it defaults to -std=c++14.
There are even more very handy warnings that are not enabled by the above seemingly comprehensive options:
Actually if you can get hold of the latest version of g++ (6.1), it defaults to -std=c++14.
No it defaults to -std=gnu++14. If you want to disable the gcc hacks you still need to use the -std=c++14 flag and either the -pedantic or -pedantic-errors flag.
@Others: Thanks for the hints. My g++ command was already an alias for -std=c++14 -ansi -Wpedantic. I will add -Wall and -Wextra. And i guess it's better to show the people here in the forum the options i'm using on compilation. Will not use alias anymore.