I am new to C++. I was recently making a small program that uses classes in separate file. I also want to use the setter and getter (set & get) functions to assign value to a variable. The compiler gives me a weird error when i run the program. it says 'string' does not name a type. Here is the code:
MyClass.h
#ifndef MYCLASS_H // #ifndef means if not defined
#define MYCLASS_H // then define it
#include <string>
class MyClass
{
public:
// this is the constructor function prototype
MyClass();
void setModuleName(string &);
string getModuleName();
private:
string moduleName;
};
#endif
MyClass.cpp file
#include "MyClass.h"
#include <iostream>
#include <string>
using namespace std;
MyClass::MyClass()
{
cout << "This line will print automatically because it is a constructor." << endl;
}
void MyClass::setModuleName(string &name) {
moduleName= name;
}
string MyClass::getModuleName() {
return moduleName;
}
main.cpp file
#include "MyClass.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
MyClass obj; // obj is the object of the class MyClass
obj.setModuleName("Module Name is C++");
cout << obj.getModuleName();
return 0;
}