Trouble declaring string member in class header file

My compiler keeps generating an error message when I try to declare a string member in a class declaration. I've tried including <string> in both the .cpp and the .h files, but that doesn't seem to help. What am I doing wrong?

The error message is:
error C2146: syntax error : missing ';' before identifier 'name'

And it points to the line
string name;

The program is supposed to allow the user to play Battleship, btw.

HEADER:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#ifndef SHIP_H
#define SHIP_H

class Coordinates;
enum Ship_t;

class Ship {
public:
	Ship();
	void set( Ship_t s_type );
	Ship_t get_type();
	void get_hit();
	int get_health();
	int get_max();
	void place_ship( Coordinates first, Coordinates second );

private:
	string name;
	Ship_t type;
	int max_health;
	int health;
	bool placed;
	Coordinates coord1, coord2;
};

#endif 


SOURCE CODE FILE
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include "Ship.h"
#include "Enums.h"
#include "Coordinates.h"
#include <iostream>
#include <string>
using namespace std;

Ship::Ship()
{
	name = "none";
	type = NONE;
	max_health = 1;
	health = 0;
	placed = false;
	coord1.set_coordinates( ERR, 1 );
	coord2.set_coordinates( ERR, 2 );
}

void Ship::set( Ship_t s_type )
{
	type = s_type;
}

Ship_t Ship::get_type()
{
	return type;
}

void Ship::get_hit()
{
	health--;
}
	
int Ship::get_health()
{
	return health;
}

int Ship::get_max()
{
	return max_health;
}

void Ship::place_ship( Coordinates first, Coordinates second )
{
	coord1 = first;
	coord2 = second;
}
Last edited on
You need a #include <string> in your header file.
And the use std::string for declaring the member.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#ifndef SHIP_H
#define SHIP_H

#include <string> // ****

class Coordinates;
enum Ship_t;

class Ship {
public:
        // ...
private:
	//string name;
       std::string name ; // ****
};
#endif  
Hmmm, ok, that fixes it. I guess I just figured that having the source code file Ship.cpp include <string> and using namespace std would be sufficient. I thought I had gotten away with that before in other programs but maybe I'm mistaken. Thanks
dpan wrote:
Hmmm, ok, that fixes it. I guess I just figured that having the source code file Ship.cpp include <string> and using namespace std would be sufficient.


It would have worked if only you had put the #includes in the source file in the right order.
Last edited on
Topic archived. No new replies allowed.