Problem with std::string in header file

i have problem with string when use header file.
My code in header file in following
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iosfwd>

#ifndef SINHVIEN_H_
#define SINHVIEN_H_

class Sinhvien {
private:
	int age;
	std::string namesv;
public:
	Sinhvien();
	Sinhvien(std::string, int);
	virtual ~Sinhvien();
    int getAge() const;
    std::string getName() const;
};

#endif 

And here's my cpp 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
#include "../headers/sinhvien.h"
#include "string"

using namespace std;

Sinhvien::Sinhvien() {
	namesv = "";
	age = 0;
}

Sinhvien::Sinhvien(string namesv, int age)
{
	this->namesv = namesv;
	this->age = age;
}

int Sinhvien::getAge() const
{
    return age;
}

string Sinhvien::getName() const
{
    return namesv;
}

Sinhvien::~Sinhvien() {
	// TODO Auto-generated destructor stub
}

And my errors
1
2
3
4
5
6
7
8
..\src\cpps\../headers/sinhvien.h:9: error: field 'namesv' has incomplete type
..\src\cpps\sinhvien.cpp: In constructor 'Sinhvien::Sinhvien()':
..\src\cpps\sinhvien.cpp:7: error: 'namesv' was not declared in this scope
..\src\cpps\sinhvien.cpp: In constructor 'Sinhvien::Sinhvien(std::string, int)':
..\src\cpps\sinhvien.cpp:13: error: 'class Sinhvien' has no member named 'namesv'
..\src\cpps\sinhvien.cpp:13: error: 'name' was not declared in this scope
..\src\cpps\sinhvien.cpp: In member function 'std::string Sinhvien::getName() const':
..\src\cpps\sinhvien.cpp:24: error: 'namesv' was not declared in this scope

I don't know why std::string causes error in here ? If I don't use string (by the way replace string by int), everything's normal !
Last edited on
If you are using std::string than most likely the header is in system path.

#include "string"

Change above to #include<string> and see how.

And also usually for system headers we include them in our .h file instead of .cpp file by convention. This help us to put all system headers at a centralized place for easier reference. Then the .cpp will include the .h which will see those system headers already.
Sorry ! I know where cause error ! Without #include<string> in header file ! :)
Topic archived. No new replies allowed.