bant
bant

Reputation: 11

c++ class declaration error?

guys i am new to c++ i am trying to create an class these are my files

//main.cpp
#include <iostream>
#include "testing/test.h"
#include <string>
using namespace std;


int main(void)
{

 test c;
 c.set_url("e");

}

test.h

#ifndef TEST_H_
#define TEST_H_
#include<string>
class test {

  public:

    void testing(string url);


};

#endif /* TEST_H_ */



     //test.cpp

#include <iostream>
#include<string>
using namespace std;



void crawl::testing (string url) {
 cout<< "i am from test class";
}

i am getting error: ‘string’ has not been declared error

Upvotes: 1

Views: 1333

Answers (2)

Greg Domjan
Greg Domjan

Reputation: 14125

The error you are getting is from not using the namespace std in the header file ie. std::string and not having the using namespace std; before your inclusion of the header file (or in the header).

The command using namespace std; is saying assume a class may be in this namespace, but it only applies to all the uses after the command.

If you did this instead it would also work, though in general this is bad form.

#include <string>
using namespace std;
#include "testing/test.h"

Also, don't forget to include test.h into test.cpp.

Upvotes: 1

JaredPar
JaredPar

Reputation: 755507

The problem is you need to use the fully qualified name of string since the std namespace is not imported

class test {
public:
  void testing(std::string url);
};

Please avoid the temptation to fix this by using the std namespace within the testing.h file. This is generally speaking bad practice as it can change the way names are resolved. It's much safer, albeit a bit annoying, to qualify names in header files.

Upvotes: 5

Related Questions