Reputation: 99
Pretty simple question but I couldn't find an answer regarding this specific question which surprised me.
I get a string of errors when attempting to call a class function that changes a private class string.
Edit: I have solved the problem - I forgot to include the required namespace and assembly references in the header file.
Here is the .h file code:
#ifndef ANIMAL_H
#define ANIMAL_H
class Animal
{
public:
Animal();
~Animal();
string getName();
void setName(string animalName);
private:
string name;
};
#endif
here is the class .cpp:
#include "Animal.h"
#include <iostream>
#include <string>
#include <conio.h>
using namespace std;
Animal::Animal()
{
}
Animal::~Animal()
{
}
void Animal::setName(string animalName)
{
name = animalName;
}
string Animal::getName()
{
return name;
}
finally,here is the int main(),where I have attempted to call the functions (I just got a bunch of errors upon compiling)
int main()
{
Animal chicken;
chicken.setName("gary");
cout << chicken.getName() << endl;
_getch();
}
Error messages include:
error C2061: syntax error : identifier 'string'
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
`error C2146: syntax error : missing ';' before identifier 'getName'`
Upvotes: 0
Views: 846
Reputation: 1368
Your class header is missing string library declaration and std:: before each string declaration.
#ifndef ANIMAL_H
#define ANIMAL_H
#include <string>
class Animal
{
public:
Animal();
~Animal();
std::string getName();
void setName(std::string animalName);
private:
std::string name;
};
#endif
@edit Up
You beat me to it! Your answer showed up just when I posted mine
Upvotes: 0
Reputation: 20103
Looks like you forgot to include <string>
in your header. The string object also lives in the std
namespace so you need provide a fully qualified name to use it (don't add using namespace
to headers).
#ifndef ANIMAL_H
#define ANIMAL_H
#include <string> // You need to include this
class Animal
{
public:
Animal();
~Animal();
std::string getName();
void setName(std::string animalName);
private:
std::string name;
};
#endif
Upvotes: 1