Search code examples
c++stringheaderidentifier

String declaration problems c++


I was trying to compile this simple program but whenever I try to compile it it gives me many errors and all are string related errors like "syntax error:identifier 'string' " and "undeclared identifier" for my string function and variable. I tried to delete using namespace std; and using std::string instead but still the same errors occur. I am using Visual Studio 2017.

#include "Animal.h"
#include <iostream>
#include <string>
using namespace std;

int main() {
    Animal Cat;

    cin.get();
}

and thats the Animal.h:

class Animal
{
public:
    Animal();

    void SetAnimalName(string x);
    string GetName();

    void SetAnimalAge(int y);
    int GetAnimalAge();

private:
    string AnimalName;
    int AnimalAge;
};

Animal.cpp

#include "Animal.h"
#include <iostream>
#include <string>
using namespace std;

Animal::Animal()
{
    AnimalName = "cat";
    AnimalAge = 3;
    std::cout << "the Animal is: " << AnimalName << std::endl << "its Age is: " << AnimalAge;
}

void Animal::SetAnimalName(string x) {
    AnimalName = x;
}
string Animal::GetName() {
    return AnimalName;
}
void Animal:: SetAnimalAge(int y) {
    AnimalAge = y;
}
int Animal::GetAnimalAge() {
    return AnimalAge;
}

Solution

  • You are missing the #include <string> in your Animal.h which breaks the compilation of your main.cpp.

    You are also missing std::string in your Animal.h. As a general rule of thumb, don't use using namespace std and stick with prefixing standard library functions with the std namespace (std::string in your case).