Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/forums/cpp/)
-   -   String in header file not working (http://www.go4expert.com/forums/string-header-file-t16291/)

Daviking 21Feb2009 11:27

String in header file not working
 
I am a beginning programmer, with almost no knowledge whatsoever. I am trying to make a very simple program with one header file, just to test out the principle. However, I cannot seem to get it to work. Whenever I try to compile, I get this error:

in header file, 'string' does not have a type
invalid conversion from 'const char*' to 'int'

Here is my source code:

//MULTIFILE.CPP (source file)
#include <iostream>
#include <string>
#include "Multifile.h"
using namespace std;
int main()
{
cout << "Tripling 9: " << times3(9) << endl;
cout << "Tripling 'game': " << times3("hello") << "\n\n";
return 0;
}

//MULTIFILE.H (header file)
#ifndef MULTIFILE_H
#define MULTIFILE_H
int times3(int number) { return (number * 3); }
string times3(string text) { return (text + text + text); }
#endif

I have tried different "using" and std::string things in both the source and header, tried #including string in the header, and nothing seems to work... I keep getting the error. It does not seem to have anything to do with function overloading, and I am stuck.

Please help!

xpi0t0s 21Feb2009 13:51

Re: String in header file not working
 
Move the "using" above the #include "Multifile.h" line.

It's not a good idea to put function bodies in a header file because if that header file is included in more than one source file (which is the point of header files, so if you only have one source file you don't need one) then you're going to get duplicate symbols. So just get it all working in one file before splitting it out into headers.

This all works fine in Visual Studio 2005 (main() just calls FUNC() which stops me needing millions of projects for go4e code testing):
Code:

#include <iostream>

#define FUNC go4e_16291

#include <string>
using namespace std;

int times3(int number) { return (number * 3); }
string times3(string text) { return (text + text + text); }

void go4e_16291()
{
cout << "Tripling 9: " << times3(9) << endl;
cout << "Tripling 'game': " << times3("hello") << "\n\n";
}

Output:
Tripling 9: 27
Tripling 'game': hellohellohello

Daviking 21Feb2009 22:17

Re: String in header file not working
 
Thank you. This works now.


All times are GMT +5.5. The time now is 13:11.