-4

This has to be a bug (the error in the title), but does anyone know how to fix it or just get around it?

Here is the code (I also have two other files which are having the same problem):

#include <iostream>
#include <string>

class Person
{
public:
    Person(): name(""), dob(""), gender("") { }
    Person(string n, string d, string g): name(n), dob(d), gender(g) { }
    virtual void print() { cout << name << " " << dob << endl; }
protected:
    string name;
    string dob;
    string gender;
};

Every instance of "string" in the code above receives the "unable to resolve identifier string" error.

It also is not able to resolve the identifier "cout" and "endl." Again, does anyone know a workaround or some kind of fix? Any help is appreciated, thanks.

user2628156
  • 381
  • 3
  • 5
  • 13

2 Answers2

6

cout, endl, and string are not in the global namespace. They are inside std.

You need to use std::cout, std::endl, std::string instead.

If you want to avoid appending std:: every time, you can use using.

Put these after the includes:

using std::cout;
using std::endl;
using std::string;
HoiHoi-san
  • 61
  • 2
2

The problem is that cout, string, and endl are all symbols defined in the namespace std. If you do not qualify them or introduce those names into the local or enclosing namespace they will be not be found by the compiler. To qualify them, prepend the name std::. For example,

protected:
    std::string name;
    std::string dob;
    std::string gender;

You would also do the same for other standard names. Another option is to use a using statement, like this:

using std::string;
using std::cout;
using std::endl;

You also might be tempted to use using namespace std, but for several reasons this usage is deemed a bad practice. Do not use it.

Community
  • 1
  • 1
David G
  • 94,763
  • 41
  • 167
  • 253