-2

I am new in C++. When I compile this code compiler reports error-

main.cpp-

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

using namespace std;

string strings::getstr(string str)
{
    return str;
}

int main()
{
    strings strstr;
    string constr;
    string msg;

    msg = "Hello World!";
    constr = strstr.getstr(msg);
    cout << constr;
    return 0;
}

main.h-

#ifndef MAIN_H_INCLUDED
#define MAIN_H_INCLUDED

#include <string>

class strings
{
public:
    string getstr (string str);
};

#endif // MAIN_H_INCLUDED

error-

error: 'string' does not name a type
error: no 'std::string strings::getstr(std::string)' member function declared in class 'strings'
error: In function 'int main()':
error: 'class strings' has no member named 'getstr'

I am using Code::Blocks and gcc I have written this simple code because I am working on a project and when I want to compile I always getting

'string' does not name a type

sorry for bad english...

Mominul
  • 67
  • 8

3 Answers3

0

The correct name for the string class is 'std::string' because it is declared within the 'std' namespace (the same goes for 'cout'). After you change 'string' into 'std::string' and use 'std::cout' instead of 'cout' your program will compile correctly.

Another way to do it is to place 'std' the as the first namespace:

#include <string>
using namespace std;

Personally, I don't like to use 'using namespace ...' (It's difficult for me to keep track of different namespaces ).

Adolfo
  • 281
  • 2
  • 5
  • 1
    `using namespace std` does not make `std` the "default" namespace (that concept doesn't exist in the language.) It is also a terrible idea to do that in a header file. – juanchopanza Dec 25 '14 at 18:25
-1

This could fix the problem

#ifndef MAIN_H_INCLUDED
#define MAIN_H_INCLUDED

#include <string>

class strings
{
public:
    std::string getstr(std::string str);
};

#endif // MAIN_H_INCLUDED
David G
  • 94,763
  • 41
  • 167
  • 253
Mohamed Ali
  • 173
  • 5
-2

use using namespace std; after the header in main.h

Ali Akber
  • 3,670
  • 3
  • 26
  • 40