0

main.cpp:

#include <iostream>
#include "PrintText.h"
#include <string>

using namespace std;

int main()
{
PrintText tOb("Mwhahahaahhaha");
cout << tOb.getText() << endl;
return 0;
}

PrintText.cpp:

#include "PrintText.h"
#include <iostream>
#include <string>

using namespace std;

PrintText::PrintText(string z){
setText(z);
}

void PrintText::setText(string x){
text = x;
}

string PrintText::getText(){
return text;
}

PrintText.h:

#ifndef PRINTTEXT_H
#define PRINTTEXT_H

class PrintText{
public:
PrintText(string z);
void setText(string x);
string getText();
private:
string text;
};

#endif

I'm getting errors saying that string has not been declared and string does not name a type in my .h file and I don't understand why.

2 Answers2

4
  • Put #include <string> in your header file before your declarations

  • Use std::string instead of string

  • Never ever place a using namespace statement in a header file

Sebastian Hoffmann
  • 11,127
  • 7
  • 49
  • 77
  • Thanks it works fine now. But I have another couple questions if you don't mind answering them. 1. How do I know when to use std:: is there a list of data types etc. that it can be use it for so that I know for future programs. 2. Why can you not use using namespace in a .h file. – user3381220 Mar 04 '14 at 23:44
  • 2) [why-is-using-namespace-std-considered-bad-practice](http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – Mooing Duck Mar 04 '14 at 23:45
  • @user3381220 All types and functions of the standart library (everything you can include "plug and play like") are in the `std` namespace. 2) `using namespace` basically reverts namespaces and should therefor only be used if you explicitely know what you are doing (like casts). However if you place it in a header you basically "force" it upon everyone using your class/header without them being able to decide whether they want so or not. – Sebastian Hoffmann Mar 04 '14 at 23:48
2

Modify the header file as following

#ifndef PRINTTEXT_H
#define PRINTTEXT_H
#include <string>

class PrintText{
public:
    PrintText(std::string z);
    void setText(std::string x);
    std::string getText();
private:
    std::string text;
};

#endif

And you don't need to include #include <string> again in the .cpp file.

CroCo
  • 5,531
  • 9
  • 56
  • 88