andylcx@hotmail.com wrote:[color=blue]
> Hi all, I wrote a class, but met some exception when I call its member
> function. How to fix it? Thanks. My code is shown below:
>
> class Myclass
> {
> public:
> Myclass();
> ~Myclass();
> double *showdata();
>
> private:
> double *data;
> };
>[/color]
You seem to have forgotten to give the definition of the ctor and the
dtor. Assuming you have a blank ctor and dtor. Lets move ahead.
[color=blue]
> double *Myclass::showdata()
> {[/color]
Memory has to be allocated for data. I would write:
data = new double[10];
[color=blue]
> for(int i=0;i<10;i++)
> data[i]=double (i);
> return data;
> }
>
> My main function
> #include <...>
> int main()
> {
> Myclass *newclass = new Myclass;
> newclass->showdata();//Here is the problem. what is the return value[/color]
The above statement causes seg fault because you forgot to allocate
memory to a pointer in showdata(). BTW, why do you need to return the
doubel array.
You could write another accessor function or use the same function to
display the values.
[color=blue]
> delete newclass;[/color]
Similar to this statement yo also need to de-allocate memory for data
by writing
delete []data;
in your showdata() function.
thanks!! and have a nice day!!
jaspreet[color=blue]
> }[/color]