1

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!

3 Answers 3

4

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.