string and classes OMG:)
Oct 8, 2011 at 4:56am UTC
i want to put strings in to my classes. But it doesn't work. Does anyone know how strings and classes work?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
//test.h
#ifndef TEST_H
#define TEST_H
#include <string>
class Test
{
public :
Test(const string &);
void setName(const string &);
string getName();
private :
string name;
};
#endif
//------------
#include <iostream>
#include <string>
#include "Test.h"
using namespace std;
Test::Test(const string &n):name(n)
{
}
void Test::setName(const string &sName)
{
name=sName;
}
string Test::getName()
{
return this ->name;
}
//---------------
#include <iostream>
#include <string>
#include "Test.h"
using namespace std;
int main()
{
Test t("Jason" );
t.getName;
system("pause" );
return 0;
}
Thanks!!!:)
Last edited on Oct 8, 2011 at 4:57am UTC
Oct 8, 2011 at 6:10am UTC
Line 49 should be t.getName();
Oct 8, 2011 at 6:20am UTC
All your references to string in test.h should be std::string . By the way, it's a bad idea to put a using statement in a header file, so don't put using namespace std;
int test.h. Instead use the fully qualified name std::string .
Oct 8, 2011 at 6:32am UTC
i still didn't get it. I hope this is the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
//test.h
#ifndef TEST_H
#define TEST_H
class Test
{
public :
Test(const string &);
void setName(const string &);
string getName();
private :
std::string name;
};
#endif
//------------
#include <iostream>
#include <string>
#include "Test.h"
//using namespace std;
Test::Test(std::string &n):name(n)
{
}
void Test::setName(std::string &sName)
{
name=sName;
}
string Test::getName()
{
return name;
}
//---------------
#include <iostream>
#include <string>
#include "Test.h"
using namespace std;
int main()
{
Test t("Jason" );
t.getName();
system("pause" );
return 0;
}
it doesn't work. Only for string i have to mension std::string right?
:(
Last edited on Oct 8, 2011 at 6:34am UTC
Oct 8, 2011 at 6:55am UTC
thanks .....It works perfectly....... U guys are great.....Thanks a lot again
:) :D :P :) :) :B :D :D :D :D :D :D
Topic archived. No new replies allowed.