questions on string in the class
Apr 8, 2011 at 5:02am UTC
i'm newbie in c++, so i expect some of the c++ expert to help me.
i'm not familiar with string in c++ especially when using string in class
the question is:
i use string "name" as a attribute of a class,
and use main.cpp to setup a object of that class,
when i run this program
an unknown run time error appear.
can any experts tell me wat problem is it?
here is the code:
cat main.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
#include "person.h"
using namespace std;
void print(const person p);
int main()
{
person me;
me.setUpPerson("Ivan" , 23);
print(me);
system("pause" );
return 0;
}
void print(person p)
{
cout << "I'm " << p.getName() << " and I'm " << p.getAge() << " year-old!!" << endl;
}
cat person.h
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
#include <iostream>
#include <string>
using namespace std;
class person
{
private :
string *name;
int age;
public :
person() : name(NULL), age(0){}
person(const person &other) : name(other.name), age(other.age){}
~person(){
delete [] name;}
void setUpPerson(string nameT, int ageT){
*name = nameT;
age = ageT;}
string* getName(){
return name;}
int getAge(){
return age;}
};
Apr 8, 2011 at 5:07am UTC
You aren't supposed to use strings like that. Just make a normal string and you can use it pretty intiutively:
1 2 3 4
std::string str;
str = "cat" ;
str += "s are" ;
std::cout<<str; //prints "cats are"
You also won't need a copy-ctor or a destructor in that case.
Apr 8, 2011 at 5:19am UTC
okay, does it mean that i have to use char in here instead of using string??
otherwise, how can i input name from main.cpp into person object
Apr 8, 2011 at 5:50am UTC
Don't use a string*, just change it to string. You'll have to change some of your uses of it around though.
Apr 8, 2011 at 5:55am UTC
Also, the parameter for the function prototype
void print(const person p)
on line 5 differs from that of the function implementation on line 16. In the prototype you are passing a person object by value which will make a copy of the parameter for use inside the function so the
const qualifier would be superfluous. You probably meant to pass by
const reference so change line 5 to:
void print(const person& p);
and change line 16 to:
1 2 3 4
void print(const person& p)
{
cout << "I'm " << p.getName() << " and I'm " << p.getAge() << " year-old!!" << endl;
}
The
const qualifier is appropriate since your
print function does not change its parameter.
Apr 8, 2011 at 6:07am UTC
oh, ya, thanks experts
Topic archived. No new replies allowed.