thlgood
thlgood

Reputation: 1295

"string is not a type" in namespace

I write a program in c++ with two files.

main.cpp

#include "var.hpp"
#include <iostream>
using namespace std;
using namespace YU;

int main()
{
    string god = "THL";
    age = 10;
    cout << age << endl;
    cout << god << endl;
    return 0;
}

var.hpp

#ifndef __VAR_H__
#define __VAR_H__

#include <string>

namespace YU
{
    int age;
    string name;
}

#endif

When I compilered it, It'get wrong.

the wrong infomation is:

In file included from main.cpp:1:0:

var.hpp:9:5: Error: ‘string’ is not a type name

I don't know why,I had include <string> head file, but it still dosen't work.

I write this code just for practice, not for work.

thank you!

Upvotes: 1

Views: 5170

Answers (3)

drew212
drew212

Reputation: 506

Alternativly you could use

using std::string;

This avoids having to type std::string in front of every string, and you don't grab everything from the global namespace.

Upvotes: 1

huon
huon

Reputation: 102076

The problem is the namespace of string in var.hpp. string is the std namespace, but you are not telling the compiler that. You could fix it by putting using namespace std; in var.hpp, but the following is a better solution as it doesn't clutter the global namespace with other things from std:

#ifndef __VAR_H__
#define __VAR_H__

#include <string>

namespace YU
{
    int age;
    std::string name;
}

#endif

Upvotes: 4

Matthew Schulkind
Matthew Schulkind

Reputation: 181

You have using namespace std; in your .cpp file, but it comes after the include of var.h. If you're going to write the header like that, you should put using namespace std; in the header as well.

Upvotes: 1

Related Questions