hi
I'm trying to create a member function of a class which takes a variable of the class type and uses its values to output a string. heres my constructor:
1 2 3 4 5 6 7 8 9 10
|
Intclass::Intclass(int x)
{
vector <int> val;
int i = 0;
while(x != 0)
{
val.push_back( x%10 );
x /= 10;
}
}
|
this takes an int and puts it into a vector (units, tens etc..), which seems to work fine.
Having created a variable of type Intclass with some numbers in I then want to have a member function which will output them as a string which I've written like this:
1 2 3 4 5 6 7 8 9
|
string Intclass::st() const
{
string s;
for (int i = 0; i < val.size(); ++i){
s.push_back( val[i] );
}
cout << s << val.size();
return s;
}
|
when I then try using the function (b.st(); where b is the variable) it doesn't output anything and cout's val.size() as being '0' if I try to access elements of val[] I go out of bounds, and get a segmentation fault, as it seems to no longer exist.
what I'm confused about is what happened to the private member of my variable of type Intclass, val, which was where my list of numbers is stored, and is there a problem with my constructor? or am I trying to access the private member incorrectly? why is my vector now apparently empty? and zero elements long?
thanks in advance for any help. I feel like i've missed something quite basic about how to use classes although for the life of me I can't see what I've done differently from other examples which seem to pass these values around fine.